diff options
author | Sebastian Porto <s@porto5.com> | 2021-01-20 03:16:49 +1100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-01-19 16:16:49 +0000 |
commit | 637e1f46bddbee4a4bb8a85e5c61e54d9197a57d (patch) | |
tree | b0cbfd94b27bf2843bdd234813b4b85091332605 /src | |
parent | 400cd752db3e04dcad8bf2a199a4d136ed85cedc (diff) | |
download | gleam_stdlib-637e1f46bddbee4a4bb8a85e5c61e54d9197a57d.tar.gz gleam_stdlib-637e1f46bddbee4a4bb8a85e5c61e54d9197a57d.zip |
Add list.window and list.window_by_2 (#156)
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/list.gleam | 42 |
1 files changed, 42 insertions, 0 deletions
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)) +} |