Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- The `list` module gains the `flat_map` function.
- The `option` module gains the `values` function.
- The `result` module gains the `values` function.
- All modules now use the new `#(a, b, ...)` tuple syntax.
Expand Down
14 changes: 14 additions & 0 deletions src/gleam/list.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,20 @@ pub fn flatten(lists: List(List(a))) -> List(a) {
do_flatten(lists, [])
}

/// Map and flatten the result
///
/// ## Examples
///
/// ```
/// > flat_map([2, 4, 6], fn(x) { [x, x + 1] })
/// [2, 3, 4, 5, 6, 7]
/// ```
///
pub fn flat_map(over list: List(a), with fun: fn(a) -> List(b)) -> List(b) {
map(list, fun)
|> flatten
}

/// Reduces a list of elements into a single value by calling a given function
/// on each element, going from left to right.
///
Expand Down
5 changes: 5 additions & 0 deletions test/gleam/list_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,11 @@ pub fn flatten_test() {
|> should.equal([1, 2, 3, 4])
}

pub fn flat_map_test() {
list.flat_map([1, 10, 20], fn(x) { [x, x + 1] })
|> should.equal([1, 2, 10, 11, 20, 21])
}

pub fn fold_test() {
[1, 2, 3]
|> list.fold([], fn(x, acc) { [x, ..acc] })
Expand Down