BoxesEdit on GitHub
Value bindings in Grain are immutable, which means that they do not change after they have been declared. While there’s a ton we can get done with regular bindings, it can sometimes be helpful to change the data already associated with a name. This is accomplished with what we call “boxes.”
Take a look at the following example:
A couple things to note from this example:
- We use the built-in
boxfunction to create a box.
- We use a caret (
^) to retrieve a value from a box. We call this “unboxing.”
- We use
:=to update the value in a box.
Just like any other binding in Grain, boxes are immutable. The box itself cannot be swapped out for another box (or anything else for that matter). However, the contents of boxes can be changed.
Boxes are commonly used with numbers, so Grain ships with some operators to make working with boxed numbers easier. Grain provides