Skip to content

Commit 26271b6

Browse files
giacomocavalierilpil
authored andcommitted
Add list.map3
1 parent 7999445 commit 26271b6

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

CHANGELOG.md

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

55
- The `list` module gains the `list.map2` function.
6+
- The `list` module gains the `list.map3` function.
67

78
## v0.29.2 - 2023-06-21
89

src/gleam/list.gleam

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,33 @@ fn do_map2(
412412
}
413413
}
414414

415+
/// Combines three lists into a single list using the given function.
416+
///
417+
/// If a list is longer than the others the extra elements are dropped.
418+
///
419+
pub fn map3(
420+
list1: List(a),
421+
list2: List(b),
422+
list3: List(c),
423+
with fun: fn(a, b, c) -> d,
424+
) -> List(d) {
425+
do_map3(list1, list2, list3, fun, [])
426+
}
427+
428+
fn do_map3(
429+
list1: List(a),
430+
list2: List(b),
431+
list3: List(c),
432+
fun: fn(a, b, c) -> d,
433+
acc: List(d),
434+
) -> List(d) {
435+
case list1, list2, list3 {
436+
[], _, _ | _, [], _ | _, _, [] -> reverse(acc)
437+
[a, ..as_], [b, ..bs], [c, ..cs] ->
438+
do_map3(as_, bs, cs, fun, [fun(a, b, c), ..acc])
439+
}
440+
}
441+
415442
/// Similar to `map` but also lets you pass around an accumulated value.
416443
///
417444
/// ## Examples

test/gleam/list_test.gleam

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,29 @@ pub fn map2_test() {
189189
list.map2(list, list, int.add)
190190
}
191191

192+
pub fn map3_test() {
193+
let add3 = fn(x, y, z) { x + y + z }
194+
195+
list.map3([], [1, 2, 3], [4, 5, 6], add3)
196+
|> should.equal([])
197+
198+
list.map3([1, 2, 3], [], [4, 5, 6], add3)
199+
|> should.equal([])
200+
201+
list.map3([1, 2, 3], [4, 5, 6], [], add3)
202+
|> should.equal([])
203+
204+
list.map3([1, 2, 3], [4, 5], [6], add3)
205+
|> should.equal([11])
206+
207+
list.map3([1, 2, 3], [4, 5, 6], [7, 8, 9], add3)
208+
|> should.equal([12, 15, 18])
209+
210+
// TCO test
211+
let list = list.repeat(0, recursion_test_cycles)
212+
list.map3(list, list, list, add3)
213+
}
214+
192215
pub fn map_fold_test() {
193216
[1, 2, 3, 4]
194217
|> list.map_fold(from: 0, with: fn(acc, i) { #(acc + i, i * 2) })

0 commit comments

Comments
 (0)