Options
Creating and using options
A type foo?
is an optional foo
.
An option can be empty (have no value inside) or non-empty (have a value inside).
This is useful for values that, in other languages, might be a special value like
null
or -1
.
Explicitly making the value optional means that you won't have to remember that.
Above you can see the most common way of using an option:
if
with ?=
.
The unwrapped value of the option becomes x
,
or if the option was empty, the else
branch will run.
These can integrate with other if
chains.
"??" and "||"
The ??
operator provides a default value for an option if it's empty.
The ||
operator is similar, but it takes two options and returns another option.
Forcing an option
Use x!
to get the value of an option or throw an exception if it is empty.
(Exceptions will be explained in Exceptions.)
Optional calls
In contrast with forcing an option, x?.f
calls f
only if x
is non-empty.
You can also use x?[y]
to optionally subscript.
Option conditions
The left hand side of ?=
is a destructure.
Here _, x
destructures a (nat, string)
.
Other expressions besides if
can use option conditions too.
Here's an example with guard
:
It works in while
or until
loops too.
For a while
loop, the variable is only visible inside the loop.
For an until
loop, the variable is only visible after the loop.