What would be the maybe monad in ZIG language.
Here a link for other languages,
I suppose the closest would be optional types, which are typed ?T
; an instance of ?T
can either be a value of T
, or null
. There are a few ways to unwrap an optional value:
optional orelse expr
: if non-null, will evaluate to the value wrapped inside the optional, otherwise evaluates toexpr
.if (optional) |value| {...}
: if non-null,value
is the unwrapped value, available within the expression pertaining to theif
statement/expression. Can optionally have anelse {...}
clause. The capture can also be made to point at the value’s location itself, by writing it as|*value|
.while (optional) |value| {...}
: same idea as unwrapping using anif
statement/expression, with the main difference being that thewhile
loop will continue untiloptional
isnull
; this is often used whereinoptional
is actually a function call, which allows for a nice way to define iterators.optional.?
: sugar foroptional orelse unreachable
, with the added bonus of being able to be treated as an lvalue.
It can also be compared to check if it’s null
, i.e. optional == null
, so you can choose to combine that in certain situations with that last unwrapping method:
if (optional == null or optional.? != target) {...}
Also should be noted, one needn’t unwrap an optional value to assign a value to it or anything, you can simply write optional = value
or optional = null
.
One might also consider error unions, which act very similarly to optionals, with important differences, namely that they can possess multiple non-value values, as opposed to just null
, I will refrain from going into that here though.
Refs:
https://ziglang.org/documentation/master/#Optionals
https://ziglang.org/documentation/master/#Type-Coercion-Optionals
https://ziglang.org/documentation/master/#while-with-Optionals