aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md1
-rw-r--r--src/gleam/option.gleam21
-rw-r--r--test/gleam/option_test.gleam14
3 files changed, 36 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e750c3..8918f8e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +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.
## 0.9.0 - 2020-05-26
diff --git a/src/gleam/option.gleam b/src/gleam/option.gleam
index 663cd1f..46327ed 100644
--- a/src/gleam/option.gleam
+++ b/src/gleam/option.gleam
@@ -85,3 +85,24 @@ pub fn unwrap(option: Option(a), or default: a) -> a {
None -> default
}
}
+
+/// Update a value held within the Some of an Option by calling a given function
+/// on it.
+///
+/// If the option is a None rather than Some the function is not called and the
+/// option stays the same.
+///
+/// ## Examples
+///
+/// > map(over: Some(1), with: fn(x) { x + 1 })
+/// Some(2)
+///
+/// > map(over: None, with: fn(x) { x + 1 })
+/// None
+///
+pub fn map(over option: Option(a), with fun: fn(a) -> b) -> Option(b) {
+ case option {
+ Some(x) -> Some(fun(x))
+ None -> None
+ }
+}
diff --git a/test/gleam/option_test.gleam b/test/gleam/option_test.gleam
index e41c221..edbb569 100644
--- a/test/gleam/option_test.gleam
+++ b/test/gleam/option_test.gleam
@@ -40,3 +40,17 @@ pub fn unwrap_option_test() {
option.unwrap(None, 0)
|> should.equal(0)
}
+
+pub fn map_option_test() {
+ Some(1)
+ |> option.map(fn(x) { x + 1 })
+ |> should.equal(Some(2))
+
+ Some(1)
+ |> option.map(fn(x) { "2" })
+ |> should.equal(Some("2"))
+
+ None
+ |> option.map(fn(x) { x + 1 })
+ |> should.equal(None)
+}