aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAhmad Sattar <thehabbos007@gmail.com>2020-06-17 22:21:07 +0200
committerLouis Pilfold <louis@lpil.uk>2020-06-18 21:54:33 +0100
commita13164e370b17699797f616b9c8fd54a135ad490 (patch)
treee77214828832a0310d93dbf4425ecedd0defa528
parent75a5d752341cef2e35ec82752ab9b34539dba2a4 (diff)
downloadgleam_stdlib-a13164e370b17699797f616b9c8fd54a135ad490.tar.gz
gleam_stdlib-a13164e370b17699797f616b9c8fd54a135ad490.zip
Option flatten function
-rw-r--r--CHANGELOG.md2
-rw-r--r--src/gleam/option.gleam20
-rw-r--r--test/gleam/option_test.gleam14
3 files changed, 35 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8918f8e..48415df 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,7 +15,7 @@
- The `dynamic.tuple2_of` function has been renamed to `dynamic.typed_tuple2`.
- The `list.traverse` function has been renamed to `list.try_map`.
- The `list.traverse` first argument gains the label `over`.
-- Added the `map` function to the the `option` module.
+- The `option` module gains the the `map` and `flatten` functions.
## 0.9.0 - 2020-05-26
diff --git a/src/gleam/option.gleam b/src/gleam/option.gleam
index 46327ed..9a2e479 100644
--- a/src/gleam/option.gleam
+++ b/src/gleam/option.gleam
@@ -106,3 +106,23 @@ pub fn map(over option: Option(a), with fun: fn(a) -> b) -> Option(b) {
None -> None
}
}
+
+/// Merge a nested Option into a single layer.
+///
+/// ## Examples
+///
+/// > flatten(Some(Some(1)))
+/// Some(1)
+///
+/// > flatten(Some(None))
+/// None
+///
+/// > flatten(None)
+/// None
+///
+pub fn flatten(option: Option(Option(a))) -> Option(a) {
+ case option {
+ Some(x) -> x
+ None -> None
+ }
+}
diff --git a/test/gleam/option_test.gleam b/test/gleam/option_test.gleam
index edbb569..03f4186 100644
--- a/test/gleam/option_test.gleam
+++ b/test/gleam/option_test.gleam
@@ -54,3 +54,17 @@ pub fn map_option_test() {
|> option.map(fn(x) { x + 1 })
|> should.equal(None)
}
+
+pub fn flatten_option_test() {
+ Some(Some(1))
+ |> option.flatten()
+ |> should.equal(Some(1))
+
+ Some(None)
+ |> option.flatten()
+ |> should.equal(None)
+
+ None
+ |> option.flatten()
+ |> should.equal(None)
+}