Skip to content

Commit 32b56eb

Browse files
authored
Add list.flat_map (#202)
1 parent 7b10d02 commit 32b56eb

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- The `list` module gains the `flat_map` function.
56
- The `option` module gains the `values` function.
67
- The `result` module gains the `values` function.
78
- All modules now use the new `#(a, b, ...)` tuple syntax.

src/gleam/list.gleam

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,20 @@ pub fn flatten(lists: List(List(a))) -> List(a) {
452452
do_flatten(lists, [])
453453
}
454454

455+
/// Map and flatten the result
456+
///
457+
/// ## Examples
458+
///
459+
/// ```
460+
/// > flat_map([2, 4, 6], fn(x) { [x, x + 1] })
461+
/// [2, 3, 4, 5, 6, 7]
462+
/// ```
463+
///
464+
pub fn flat_map(over list: List(a), with fun: fn(a) -> List(b)) -> List(b) {
465+
map(list, fun)
466+
|> flatten
467+
}
468+
455469
/// Reduces a list of elements into a single value by calling a given function
456470
/// on each element, going from left to right.
457471
///

test/gleam/list_test.gleam

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,11 @@ pub fn flatten_test() {
165165
|> should.equal([1, 2, 3, 4])
166166
}
167167

168+
pub fn flat_map_test() {
169+
list.flat_map([1, 10, 20], fn(x) { [x, x + 1] })
170+
|> should.equal([1, 2, 10, 11, 20, 21])
171+
}
172+
168173
pub fn fold_test() {
169174
[1, 2, 3]
170175
|> list.fold([], fn(x, acc) { [x, ..acc] })

0 commit comments

Comments
 (0)