aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarcin Puc <marcin.e.puc@gmail.com>2021-03-24 09:02:37 +0100
committerLouis Pilfold <louis@lpil.uk>2021-03-27 18:50:03 +0000
commita57e5ce8385cc2b892c3c2292caf56e686d02222 (patch)
tree28b57c43fe1f48d1a7ea538491da9ce72845847b
parent19d399a9e33c3841b55a2210c8935659fe9e3400 (diff)
downloadgleam_stdlib-a57e5ce8385cc2b892c3c2292caf56e686d02222.tar.gz
gleam_stdlib-a57e5ce8385cc2b892c3c2292caf56e686d02222.zip
Make list.zip tail-recursive
-rw-r--r--src/gleam/list.gleam13
1 files changed, 8 insertions, 5 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index f2f3e5f..1fddc84 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -672,6 +672,13 @@ pub fn any(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool {
}
}
+fn do_zip(xs: List(a), ys: List(b), acc: List(tuple(a, b))) -> List(tuple(a, b)) {
+ case xs, ys {
+ [x, ..xs], [y, ..ys] -> do_zip(xs, ys, [tuple(x, y), ..acc])
+ _, _ -> reverse(acc)
+ }
+}
+
/// Takes two lists and returns a single list of 2 item tuples.
///
/// If one of the lists is longer than the other the remaining elements from
@@ -692,11 +699,7 @@ pub fn any(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool {
/// [tuple(1, 3), tuple(2, 4)]
///
pub fn zip(xs: List(a), ys: List(b)) -> List(tuple(a, b)) {
- case xs, ys {
- [], _ -> []
- _, [] -> []
- [x, ..xs], [y, ..ys] -> [tuple(x, y), ..zip(xs, ys)]
- }
+ do_zip(xs, ys, [])
}
/// Takes two lists and returns a single list of 2 item tuples.