How to push or insert into arrays?

OK, guys, this feels odd to ask, but I do not understand the following:

With self.remove(int) I can remove an element from an array.

#let a = (1, 2, 3)
#a.remove(0)

That works perfectly fine and the output type is int.
If I want to add an element to an array - say add the element “4” to a - following the Typst doc (self.push(any)) I would think you’d go for

#a.push(4)

That does not generate an error message, but neither does it render any output. The type of a.push(4) however is none.

Same goes for

#a.insert(0, 4)

No error, no rendered output, type none.

To be honest, I do not understand why?

Any explanation is appreciated.

Cheers,
Amman

I can’t explain it, but perhaps you’ll find it out yourself by trying this:

#let a = (1, 2, 3)
#a.push(4)
#a
1 Like

Thank you! I somehow thought that when using the push definition the variable is not automatically modified. So I was messing around with

#let a = (1, 2, 3)
#let b = a.push(4)

which did not work. I somehow did not try your approach, but, hey!, it works. Thanks a lot!

For what it’s worth, this is a totally reasonable assumption to make. Almost all typst functions are pure, meaning they can’t modify values outside their scope, see Function Type – Typst Documentation

In particular, all user-defined functions must be pure (though you can make them non-pure through states and counters)

1 Like

I don’t know the reasoning, but the observed behavior of the array methods is documented, even if not explicitly.

For the push method, the documentation says the following, without mentioning the return value:
Adds a value to the end of the array.

On the other hand, the documentation for the remove method mentions the return value:
Removes the value at the specified index from the array and return it.