How to Define a Dictionary with Default Values for Missing Keys in Typst?

Hello,
For a project i declared a custom function like this :

#let formatable_song(
  title,
  body_list,
  body_list_format,
  header : (
    tune : none,
    author : none,
    lyrics : none,
    pseudo : none, 
    comments : none),
) = {...}

I want to be able to “instantiate” formatable_song with header dictionary that have not all the keys like this instead of manually setting blank value to none :

#let Gaudeamus = formatable_song(
  "Gaudeamus",
  (couplet1, couplet2, couplet3, couplet4, couplet5, couplet6, couplet7),
  ("c","c","c","c","c","c","c"),
  header : (
    comments : "Les couplets marqué en gras sont ceux faits en cantus"
  )
)
// instead of this : 
#let Gaudeamus = formatable_song(
  "Gaudeamus",
  (couplet1, couplet2, couplet3, couplet4, couplet5, couplet6, couplet7),
  ("c","c","c","c","c","c","c"),
  header : (
    tune : none,
    author : none,
    lyrics : none,
    pseudo : none,
    comments : "Les couplets marqué en gras sont ceux faits en cantus"
  )
)

Before using dict i was using default value parameter but i find this solution “less” elegant.
Is there a proper way to do this ?
Thank you in advance for your responses

For this case, I generally define the following function:

// Merge two dictionaries
#let create_dict(default-dict, user-dict) = {
  let new-dict = default-dict
    for (key, value) in user-dict {
      if key in default-dict.keys() {
        new-dict.insert(key, value)
      }
    }

The default dictionary contains the default values, while the user dictionary only contains the values you want to change.

1 Like

Or a tiny bit easier: default-dict + user-dict :slight_smile:

The function declaration would then change in this way:

#let formatable_song(..., header: (:)) = {
  let header = (
    tune: none,
    author: none,
    lyrics: none,
    pseudo: none, 
    comments: none,
  ) + header
  ...
}

(you could also write header: none but I find header: (:) a bit clearer, as it suggests – to me at least – that there are no headers being set, but headers are still used)

PS: @Alex, could you maybe 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.

We hope by adhering to this, we make the information in this forum easy to find in the future. Thanks!

Understandable,
working on it ;)

1 Like