How can I create a parametrised closure in Typst?

So I’m using this package typst-theoretic and there’s a function (theorem) that I can pass another function (fmt-prefix) as argument.

I have several prefix styles that differ only in their color. Instead of writing a separate function for each color, I’d prefer to write a factory that takes a color and returns a prefix formatter with the required signature, e.g.

#let apply-color: color -> (prefix-with-color: text -> text) ???

#theorem(
  fmt-prefix: apply-color("red"),
  body: …,
  solution: …,
)

I’m unsure whether Typst lets me return a function like this. Will apply-color("red") be treated as a function value, or will it run immediately and pass its result to fmt-prefix?

The .with() method on functions is your absolute friend. It does partial application of parameters to functions.

Like this:

#let makered = text.with(red)
#makered[This text is red]

Note that even after you have applied a parameter like this, if it is a named parameter the final caller can still override it with another value, so it is very versatile that way.

1 Like

I’ve never used that package, but I guess the following might help?

#let apply-color(paint) = (
  prefix-with-color: (body) => {
    set text(fill: paint)
    body
  },
)

#let foo = apply-color(red)
#foo.at("prefix-with-color")("Test")

1 Like

Both answers work. Thank you!

I didn’t know the .with() method allowed partial functions.

https://typst.app/docs/reference/foundations/function/#definitions-with:

Returns a new function that has the given arguments pre-applied.

Pre-applied arguments is what makes function partial. You can call it infinite times.