option
Working with optional values
The option module provides helpers for option-like unions.
In Nanyx, any union that includes #some(a) is considered option-like. There is no Option(a) alias; #some(a) | #none is just the most common option-like union, and these helpers are written to preserve all non-#some tags, whatever they are.
map
Option.map: ((#some(a) | r), (a -> b)) -> (#some(b) | r)
Transforms the value when present.
#some("abc") \Option.map { .length }
-- #some(3)
def value: (#some(string) | #empty) = #some("abc")
value \Option.map { .length }
-- #some(3)
bind
Option.bind: ((#some(a) | r), (a -> (#some(b) | s))) -> (#some(b) | r | s)
Chains option-producing operations.
def a: (#some(string) | #notFound) = #some("42")
def b = a \Option.bind(int.parse) -- b: (#some(int) | #notFound | #invalidInt)
defaultValue
Option.defaultValue: ((#some(a) | r), a) -> a
Returns the wrapped value or a fallback.
Option.defaultValue(#none, 0)
-- 0
isSome
Option.isSome: (#some(a) | r) -> bool
Option.isSome(#some(10))
-- true
isNone
Option.isNone: (#some(a) | r) -> bool
Option.isNone(#none)
-- true
toResult
Option.toResult: ((#some(a) | r), e) -> #some(a) | #error(e)
Converts an option to a result with a supplied error value.
Option.toResult(#none, "missing user")
-- #error("missing user")
mapOr
Option.mapOr: ((#some(a) | r), default: b, (a -> b)) -> b
Maps the contained value or returns a default.
Option.mapOr(#some("abc"), default = 0) { .length }
-- 3
Option.mapOr(#none, default = 0) { .length }
-- 0
mapOrElse
Option.mapOrElse: ((#some(a) | r), defaultFactory: () -> b, (a -> b)) -> b
Maps the contained value or computes a fallback lazily.
Option.mapOrElse(#none, defaultFactory = { expensiveFallback() }) { .length }
For deeper background on option-like unions, see Option-like types.