#Possible to use extern dict in function?

3 messages · Page 1 of 1 (latest)

gaunt crag
#

Is something like this possible? (description below)

// library.typ
#let UseDict(key) = {
   extern MyDict // Sudocode
   let val = MyDict.at(key)
   // ... use val ...
}
// file-a.typ
#import "library.typ": *
#let MyDict = (
   "a": "x",
   "b": "y",
)

#UseDict("a") // uses value "x"; Doesn't need to pass MyDict.
// file-b.typ
#import "library.typ": *
#let MyDict = (
   "a": "foo",
   "b": "bar",
)
#UseDict("a") // uses value "foo"; Doesn't need to pass MyDict.

The goal is to be able to include that library file, define the required dictionary, and then use the function 'UseDict' without having to pass it in every call.
I know that I could create a wrapper function: #let MyUseDict(key) = UseDict(key, MyDict), but then I would have to do it in every file that has this pattern. It's not a huge deal but, if I could avoid it, then I would.

sleek atlas
# gaunt crag Is something like this possible? (description below) ``` // library.typ #let Us...

Mutable Share State

Use a "state" look at the state in documentation (it permets to have any value shared). Thisone is for having global state that is mutable (can be changed).

// main.typ
#import "package.typ" : f

#f() // return 12

#f() // return 13
// package.typ
#let d = state("d", (a : 12))

#let f() = context [
  #d.get().at("a")
  #d.update((a : d.get().at("a") + 1))
]

Immutable Share State

Want to use the fact that function have closure.

Code for the second approch (read only)

// main.typ
#import "package.typ" : f
#f() // return 12 everytime
// package.typ
#let d = (
  a : 12,
  b : 15
)

#let f() = [
  // #d.at("a") += 1 // this is not allowed 
  // #d is read only 
  #d.at("a")
]

The other way to have immutable share state is to read from a file. Any file can do it but will not be able to modify the file.

#

Tradeoff

You want to avoid as much as possible mutable state (and context) because they complexify your document and increase the iteration count of compiler introspection (there are maximum 5)