aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorthorhj <burpen@gmail.com>2024-05-22 21:53:58 +0200
committerLouis Pilfold <louis@lpil.uk>2024-05-29 12:40:03 +0100
commit8774207bf28bc66686764219fa47d9b331d14673 (patch)
tree247605754a1c21e8d8fb878aa6fde0748bb9d85e
parentd9f439c254d72e2582ee6584f97481b416a25b65 (diff)
downloadgleam_stdlib-8774207bf28bc66686764219fa47d9b331d14673.tar.gz
gleam_stdlib-8774207bf28bc66686764219fa47d9b331d14673.zip
adds count function for list
-rw-r--r--src/gleam/list.gleam31
-rw-r--r--test/gleam/list_test.gleam17
2 files changed, 48 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.
///
diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam
index dea77ff..190a49b 100644
--- a/test/gleam/list_test.gleam
+++ b/test/gleam/list_test.gleam
@@ -4,6 +4,7 @@ import gleam/int
import gleam/list
import gleam/pair
import gleam/should
+import gleam/string
@target(erlang)
const recursion_test_cycles = 1_000_000
@@ -34,6 +35,22 @@ pub fn length_test() {
|> list.length()
}
+pub fn count_test() {
+ list.count([], int.is_odd)
+ |> should.equal(0)
+
+ list.count([2, 4, 6], int.is_odd)
+ |> should.equal(0)
+
+ list.count([1, 2, 3, 4, 5], int.is_odd)
+ |> should.equal(3)
+
+ list.count(["a", "list", "with", "some", "string", "values"], fn(a) {
+ string.length(a) > 4
+ })
+ |> should.equal(2)
+}
+
pub fn reverse_test() {
list.reverse([])
|> should.equal([])