Caching function

I want the result of a function to be cached once and the function to not be called again

#let pic_cap() = {
  image-counter.step()

  context [
    #set text(hyphenate: false)
    #intro-counter.display().#image-counter.display().
  ]
}

#let pic_closer = pic_cap()

#pic_cap
#pic_cap
#pic_cap

But the function is called more than 1 time. Is it possible to retrieve the result of this function using the cache?

#let pic-cache = state("pic-cache", none)

#let pic_cap(cache-key) = {
    image-counter.step()
    context {
        let cache = state(cache-key, none)
        let cached = cache.get()
        if cached != none {
          cached
        } else {
          let result = [
            #set text(hyphenate: false)
            #intro-counter.display().#image-counter.display().
          ]
          cache.update(result)
          result
        }
    }
}

deepseek is cool

2 Likes

Hi @Nikolay1, glad you found a solution to your question. May I ask for two things?

Could you try to revise your post’s title to be a complete question as per the question guidelines:

Good titles are questions you would ask your friend about Typst.

A good title makes the topic easier to grasp. We hope by adhering to this, we make the information in this forum easy to find in the future.

Apart from that, if you’re satisfied with your solution, be sure to give it a checkmark :ballot_box_with_check:. This will help others find the solution in the future.