diff options
author | thorhj <burpen@gmail.com> | 2024-05-22 21:53:58 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2024-05-29 12:40:03 +0100 |
commit | 8774207bf28bc66686764219fa47d9b331d14673 (patch) | |
tree | 247605754a1c21e8d8fb878aa6fde0748bb9d85e /src | |
parent | d9f439c254d72e2582ee6584f97481b416a25b65 (diff) | |
download | gleam_stdlib-8774207bf28bc66686764219fa47d9b331d14673.tar.gz gleam_stdlib-8774207bf28bc66686764219fa47d9b331d14673.zip |
adds count function for list
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/list.gleam | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 2fff079..e782b45 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -65,6 +65,37 @@ fn count_length(list: List(a), count: Int) -> Int { } } +/// Counts the number of elements in a given list satisfying a given predicate. +/// +/// This function has to traverse the list to determine the number of elements, +/// so it runs in linear time. +/// +/// ## Examples +/// +/// ```gleam +/// count([], fn(a) { a > 0 }) +/// // -> 0 +/// ``` +/// +/// ```gleam +/// count([1], fn(a) { a > 0 }) +/// // -> 1 +/// ``` +/// +/// ```gleam +/// count([1, 2, 3], int.is_odd) +/// // -> 2 +/// ``` +/// +pub fn count(list: List(a), where predicate: fn(a) -> Bool) -> Int { + fold(list, 0, fn(acc, value) { + case predicate(value) { + True -> acc + 1 + False -> acc + } + }) +} + /// Creates a new list from a given list containing the same elements but in the /// opposite order. /// |