aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAhmad Sattar <thehabbos007@gmail.com>2020-06-17 22:12:52 +0200
committerLouis Pilfold <louis@lpil.uk>2020-06-18 21:54:19 +0100
commit75a5d752341cef2e35ec82752ab9b34539dba2a4 (patch)
tree719948a124c5d3cd026ff7e71730c0db78a34b7c
parent8b7f2290c67d7fc8714425785aaa14bcd781623c (diff)
downloadgleam_stdlib-75a5d752341cef2e35ec82752ab9b34539dba2a4.tar.gz
gleam_stdlib-75a5d752341cef2e35ec82752ab9b34539dba2a4.zip
Option map function
-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)
+}