Maybe monad in zig language

What would be the maybe monad in ZIG language.
Here a link for other languages,
http://www.rosettacode.org/wiki/Monads/Maybe_monad

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 to expr.
  • if (optional) |value| {...}: if non-null, value is the unwrapped value, available within the expression pertaining to the if statement/expression. Can optionally have an else {...} 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 an if statement/expression, with the main difference being that the while loop will continue until optional is null; this is often used wherein optional is actually a function call, which allows for a nice way to define iterators.
  • optional.?: sugar for optional 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

1 Like