diff options
author | Al Dee <amyalicedee@gmail.com> | 2020-05-22 20:13:11 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2020-05-26 19:19:29 +0100 |
commit | 7af5bc63628bc5ccc45fe093810292c37b354ea4 (patch) | |
tree | 4a77cf45955bddb81c260695185c94994c459033 | |
parent | 74b8029a37bc1d5470a19a6effa67763dcc32994 (diff) | |
download | gleam_stdlib-7af5bc63628bc5ccc45fe093810292c37b354ea4.tar.gz gleam_stdlib-7af5bc63628bc5ccc45fe093810292c37b354ea4.zip |
Add unwrap function to option module
-rw-r--r-- | src/gleam/option.gleam | 17 | ||||
-rw-r--r-- | test/gleam/option_test.gleam | 8 |
2 files changed, 25 insertions, 0 deletions
diff --git a/src/gleam/option.gleam b/src/gleam/option.gleam index e5be4cc..663cd1f 100644 --- a/src/gleam/option.gleam +++ b/src/gleam/option.gleam @@ -68,3 +68,20 @@ pub fn from_result(result: Result(a, e)) -> Option(a) { _ -> None } } + +/// Extract the value from an option, returning a default value if there is none. +/// +/// ## Examples +/// +/// > unwrap(Some(1), 0) +/// 1 +/// +/// > unwrap(None, 0) +/// 0 +/// +pub fn unwrap(option: Option(a), or default: a) -> a { + case option { + Some(x) -> x + None -> default + } +} diff --git a/test/gleam/option_test.gleam b/test/gleam/option_test.gleam index a6f2cc3..e41c221 100644 --- a/test/gleam/option_test.gleam +++ b/test/gleam/option_test.gleam @@ -32,3 +32,11 @@ pub fn from_result_test() { option.from_result(Error("some_error")) |> should.equal(None) } + +pub fn unwrap_option_test() { + option.unwrap(Some(1), 0) + |> should.equal(1) + + option.unwrap(None, 0) + |> should.equal(0) +} |