Named Parameters <=> Parameters with Default Values

Is there a reason why in Typst, named parameters == parameters with default values? This seems quite impractical.

Perhaps I would like to be able to have a positional parameter with a default value. For example, I can write:

#let example(arg) = [Example: #arg]

#example[
  very long text
]

But I cannot write:

#let example(arg: "Default") = [Example: #arg]

#example[
  very long text
]

Instead I have to write more verbosely:

#let example(arg: "Default") = [Example: #arg]

#example(arg: [
  very long text
])

This can become quite ugly If I have several arguments.

The other way around, perhaps I would also like to be able to have a named argument without a default value - this would allow me to specify the name when passing my argument, making my code clearer, but also making the argument mandatory (no default value). For example, I can write:

#let example(setting) = [Using a specific #setting]

#example("value")

But not the slightly clearer:

#let example(setting) = [Using a specific #setting]

#example(setting: "value")

Essentially, I don’t understand why default values and named parameters are being bound together as a single thing, when I feel like their use and advantages are relevant separately. Feel free to point me to any prior discussion about this, I didn’t find any :)

3 Likes

If you search for named arguments you will find quite a few, including:

You can actually make positional with default values, using ..arg syntax: Arguments Type – Typst Documentation

By using args.pos().at(<positional argument number>, default: <default value if not enough arguments>), you can make optiobal positional arguments with default values. Actually, it’s even more flexible than that, you can change function behaviour, for example, depending on the number of passed positional and named arguments.

And the reverse, named arguments with no default value, can be implemented very easily: set none as default value, and panic if the value is none. But I would suggest just making it positional, most code editors highlight the name of currently typed positional argument of the function, so you wouldn’t confuse them. Many languages don’t have named types at all, and sometimes it leads to better coding practices (e.g. Rust).

The approach I described above is not very ergonomic for writing functions, but actually not that bad. I think it’s a reasonable tradeoff to not add too many language constructs to a strict language like Typst.

3 Likes