diff options
author | evuez <helloevuez@gmail.com> | 2021-02-20 17:40:01 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-02-23 13:08:29 +0000 |
commit | 3a9181fc74ae1f71e109d074b0cebaba399184d0 (patch) | |
tree | 2d486aaaef756569b36b0e9935e40c01965f0b23 | |
parent | c23a6aef1e8ff9c4fc37b9f4b93e9f05e10090e6 (diff) | |
download | gleam_stdlib-3a9181fc74ae1f71e109d074b0cebaba399184d0.tar.gz gleam_stdlib-3a9181fc74ae1f71e109d074b0cebaba399184d0.zip |
Implement list.drop_while and list.take_while
-rw-r--r-- | src/gleam/list.gleam | 34 | ||||
-rw-r--r-- | test/gleam/list_test.gleam | 12 |
2 files changed, 46 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index f69e82c..662e3f7 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1219,3 +1219,37 @@ pub fn window(l: List(a), by n: Int) -> List(List(a)) { pub fn window_by_2(l: List(a)) -> List(tuple(a, a)) { zip(l, drop(l, 1)) } + +external fn erl_drop_while(fn(a) -> Bool, List(a)) -> List(a) = + "lists" "dropwhile" + +/// Drops the first elements in a given list for which the predicate funtion returns `True`. +/// +/// ## Examples +/// +/// > drop_while([1, 2, 3, 4], fun (x) { x < 3 }) +/// [3, 4] +/// +pub fn drop_while( + in list: List(a), + satisfying predicate: fn(a) -> Bool, +) -> List(a) { + erl_drop_while(predicate, list) +} + +external fn erl_take_while(fn(a) -> Bool, List(a)) -> List(a) = + "lists" "takewhile" + +/// Takes the first elements in a given list for which the predicate funtion returns `True`. +/// +/// ## Examples +/// +/// > take_while([1, 2, 3, 4], fun (x) { x < 3 }) +/// [1, 2] +/// +pub fn take_while( + in list: List(a), + satisfying predicate: fn(a) -> Bool, +) -> List(a) { + erl_take_while(predicate, list) +} diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam index 3277e47..f1acfb2 100644 --- a/test/gleam/list_test.gleam +++ b/test/gleam/list_test.gleam @@ -578,3 +578,15 @@ pub fn window_by_2_test() { |> list.window_by_2 |> should.equal([]) } + +pub fn drop_while_test() { + [1, 2, 3, 4] + |> list.drop_while(fn(x) { x < 3 }) + |> should.equal([3, 4]) +} + +pub fn take_while_test() { + [1, 2, 3, 4] + |> list.take_while(fn(x) { x < 3 }) + |> should.equal([1, 2]) +} |