A type to capture optional results; useful for handling errors.
Note that the Option type and its constructors are readily available in Aiken. They are part of the Prelude module imported by default in every module.
Functions
Inspecting
is_none
is_none(self: Option<a>) -> BoolAsserts whether an option is None.
is_some
is_some(self: Option<a>) -> BoolAsserts whether an option is Some, irrespective of the value it contains.
Combining
and_then
and_then(self: Option<a>, then: fn(a) -> Option<result>) -> Option<result>Chain together many computations that may fail.
self
|> dict.get(policy_id)
|> option.and_then(dict.get(_, asset_name))
|> option.or_else(0)choice
choice(self: List<Option<a>>) -> Option<a>Picks the first element which is not None. If there’s no such element, return None.
option.choice([]) == None
option.choice([Some(14), Some(42)]) == Some(14)
option.choice([None, Some(42)]) == Some(42)
option.choice([None, None]) == Noneflatten
flatten(opt: Option<Option<a>>) -> Option<a>Converts from Option<Option<a>> to Option<a>.
option.flatten(Some(Some(42))) == Some(42)
option.flatten(Some(None)) == None
option.flatten(None) == NoneFlattening only removes one level of nesting at a time:
flatten(Some(Some(Some(42)))) == Some(Some(42))
Some(Some(Some(42))) |> flatten |> flatten == Some(42)map
map(self: Option<a>, with: fn(a) -> result) -> Option<result>Apply a function to the inner value of an Option
option.map(None, fn(n) { n * 2 }) == None
option.map(Some(14), fn(n) { n * 2 }) == Some(28)map2
map2(
opt_a: Option<a>,
opt_b: Option<b>,
with: fn(a, b) -> result,
) -> Option<result>Combine two Option together.
type Foo {
Foo(Int, Int)
}
option.map2(Some(14), Some(42), Foo) == Some(Foo(14, 42))
option.map2(None, Some(42), Foo) == None
option.map2(Some(14), None, Foo) == Nonemap3
map3(
opt_a: Option<a>,
opt_b: Option<b>,
opt_c: Option<c>,
with: fn(a, b, c) -> result,
) -> Option<result>Combine three Option together.
type Foo {
Foo(Int, Int, Int)
}
option.map3(Some(14), Some(42), Some(1337), Foo) == Some(Foo(14, 42, 1337))
option.map3(None, Some(42), Some(1337), Foo) == None
option.map3(Some(14), None, None, Foo) == Noneor_try
or_try(self: Option<a>, compute_default: fn() -> Option<a>) -> Option<a>Like or_else but allows returning an Option.
This is effectively mapping the error branch.
option.or_try(None, fn(_) { Some("aiken") }) == Some("aiken")
option.or_try(Some(42), fn(_) { Some(14) }) == Some(42)
option.or_try(None, fn (_) { fail }) → 💥Transforming
or_else
or_else(self: Option<a>, default: a) -> aProvide a default value, turning an optional value into a normal value.
option.or_else(None, "aiken") == "aiken"
option.or_else(Some(42), 14) == 42