Skip to content

Commit 8efb599

Browse files
sportolpil
authored andcommitted
Add option.all
1 parent 32b56eb commit 8efb599

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
## Unreleased
44

55
- The `list` module gains the `flat_map` function.
6-
- The `option` module gains the `values` function.
6+
- The `option` module gains the `all` and `values` functions.
77
- The `result` module gains the `values` function.
88
- All modules now use the new `#(a, b, ...)` tuple syntax.
99

src/gleam/option.gleam

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,33 @@ pub type Option(a) {
1111
None
1212
}
1313

14+
/// Combines a list of options into a single option.
15+
/// If all elements in the list are Some then returns a Some holding the list of values.
16+
/// If any element is None then returns None.
17+
///
18+
/// ## Examples
19+
///
20+
/// ```
21+
/// > all([Some(1), Some(2)])
22+
/// Some([1, 2])
23+
///
24+
/// > all([Some(1), None])
25+
/// None
26+
/// ```
27+
///
28+
pub fn all(list: List(Option(a))) -> Option(List(a)) {
29+
list.fold_right(
30+
list,
31+
from: Some([]),
32+
with: fn(item, acc) {
33+
case acc, item {
34+
Some(values), Some(value) -> Some([value, ..values])
35+
_, _ -> None
36+
}
37+
},
38+
)
39+
}
40+
1441
/// Checks whether the option is a Some value.
1542
///
1643
/// ## Examples

test/gleam/option_test.gleam

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import gleam/should
22
import gleam/option.{None, Some}
33

4+
pub fn all_test() {
5+
option.all([Some(1), Some(2), Some(3)])
6+
|> should.equal(Some([1, 2, 3]))
7+
8+
option.all([Some(1), None, Some(3)])
9+
|> should.equal(None)
10+
}
11+
412
pub fn is_some_test() {
513
option.is_some(Some(1))
614
|> should.be_true

0 commit comments

Comments
 (0)