diff options
author | Ahmad Sattar <thehabbos007@gmail.com> | 2020-06-17 22:35:27 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2020-06-18 21:54:48 +0100 |
commit | 56228f9a5ecfef7fb968d08894a7cc4ce0dfdbae (patch) | |
tree | 05800084aed8672ef0f689af1e2e330d59c856e1 /src | |
parent | a13164e370b17699797f616b9c8fd54a135ad490 (diff) | |
download | gleam_stdlib-56228f9a5ecfef7fb968d08894a7cc4ce0dfdbae.tar.gz gleam_stdlib-56228f9a5ecfef7fb968d08894a7cc4ce0dfdbae.zip |
Option then function
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/option.gleam | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/gleam/option.gleam b/src/gleam/option.gleam index 9a2e479..2c01b4a 100644 --- a/src/gleam/option.gleam +++ b/src/gleam/option.gleam @@ -126,3 +126,34 @@ pub fn flatten(option: Option(Option(a))) -> Option(a) { None -> None } } + +/// Update a value held within the Some of an Option by calling a given function +/// on it, where the given function also returns an Option. The two Options are +/// then merged together into one Option. +/// +/// If the Option is a None rather than Some the function is not called and the +/// Option stays the same. +/// +/// This function is the equivalent of calling `map` followed by `flatten`, and +/// it is useful for chaining together multiple functions that return Options. +/// +/// ## Examples +/// +/// > then(Some(1), fn(x) { Some(x + 1) }) +/// Some(2) +/// +/// > then(Some(1), fn(x) { Some(tuple("a", x)) }) +/// Some(tuple("a", 1)) +/// +/// > then(Some(1), fn(x) { None }) +/// None) +/// +/// > then(None, fn(x) { Some(x + 1) }) +/// None +/// +pub fn then(option: Option(a), apply fun: fn(a) -> Option(b)) -> Option(b) { + case option { + Some(x) -> fun(x) + None -> None + } +} |