diff options
-rw-r--r-- | CHANGELOG.md | 1 | ||||
-rw-r--r-- | src/gleam/list.gleam | 42 | ||||
-rw-r--r-- | test/gleam/list_test.gleam | 28 |
3 files changed, 71 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d6e5b2..94a8644 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- The `list` modules gains the `window`, and `window_by_2` functions. - The `int` module gains the `clamp` function. - The `float` module gains the `clamp` function. diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 745fbf2..f32a20b 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1139,3 +1139,45 @@ pub fn permutations(l: List(a)) -> List(List(a)) { |> flatten } } + +fn do_window(acc: List(List(a)), l: List(a), n: Int) -> List(List(a)) { + let window = take(l, n) + + case length(window) == n { + True -> do_window([window, ..acc], drop(l, 1), n) + False -> acc + } +} + +/// Return a list of sliding window +/// +/// ## Examples +/// +/// ``` +/// > window([1,2,3,4,5], 3) +/// [[1, 2, 3], [2, 3, 4], [3, 4, 5]] +/// +/// > window([1, 2], 4) +/// [] +/// ``` +/// +pub fn window(l: List(a), by n: Int) -> List(List(a)) { + do_window([], l, n) + |> reverse +} + +/// Return a list of tuples containing two contiguous elements +/// +/// ## Examples +/// +/// ``` +/// > window_by_2([1,2,3,4]) +/// [tuple(1, 2), tuple(2, 3), tuple(3, 4)] +/// +/// > window_by_2([1]) +/// [] +/// ``` +/// +pub fn window_by_2(l: List(a)) -> List(tuple(a, a)) { + zip(l, drop(l, 1)) +} diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam index 3bd463a..2aa1b3e 100644 --- a/test/gleam/list_test.gleam +++ b/test/gleam/list_test.gleam @@ -536,3 +536,31 @@ pub fn permutations_test() { |> list.permutations |> should.equal([["a", "b"], ["b", "a"]]) } + +pub fn window_test() { + [1, 2, 3] + |> list.window(by: 2) + |> should.equal([[1, 2], [2, 3]]) + + [1, 2, 3] + |> list.window(3) + |> should.equal([[1, 2, 3]]) + + [1, 2, 3] + |> list.window(4) + |> should.equal([]) + + [1, 2, 3, 4, 5] + |> list.window(3) + |> should.equal([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) +} + +pub fn window_by_2_test() { + [1, 2, 3, 4] + |> list.window_by_2 + |> should.equal([tuple(1, 2), tuple(2, 3), tuple(3, 4)]) + + [1] + |> list.window_by_2 + |> should.equal([]) +} |