diff --git a/src/build/roc/Builtin.roc b/src/build/roc/Builtin.roc index e77e1f7e78e..b05b50a17c0 100644 --- a/src/build/roc/Builtin.roc +++ b/src/build/roc/Builtin.roc @@ -119,6 +119,19 @@ Builtin :: [].{ }, ) + count_if : List(a), (a -> Bool) -> U64 + count_if = |list, predicate| + List.fold( + list, + 0, + |acc, elem| + if predicate(elem) { + acc + 1 + } else { + acc + }, + ) + fold : List(item), state, (state, item -> state) -> state fold = |list, init, step| { var $state = init diff --git a/test/snapshots/repl/list_count_if.md b/test/snapshots/repl/list_count_if.md new file mode 100644 index 00000000000..ef470bbcefe --- /dev/null +++ b/test/snapshots/repl/list_count_if.md @@ -0,0 +1,13 @@ +# META +~~~ini +description=List.count_if counts elements where predicate returns true +type=repl +~~~ +# SOURCE +~~~roc +» List.count_if([1, 2, 3, 4, 5], |x| x > 2) +~~~ +# OUTPUT +3 +# PROBLEMS +NIL diff --git a/test/snapshots/repl/list_count_if_all_match.md b/test/snapshots/repl/list_count_if_all_match.md new file mode 100644 index 00000000000..18a5f8385ff --- /dev/null +++ b/test/snapshots/repl/list_count_if_all_match.md @@ -0,0 +1,13 @@ +# META +~~~ini +description=List.count_if returns list length when all elements match +type=repl +~~~ +# SOURCE +~~~roc +» List.count_if([1, 2, 3, 4, 5], |x| x > 0) +~~~ +# OUTPUT +5 +# PROBLEMS +NIL diff --git a/test/snapshots/repl/list_count_if_empty.md b/test/snapshots/repl/list_count_if_empty.md new file mode 100644 index 00000000000..d49aeb8e9e0 --- /dev/null +++ b/test/snapshots/repl/list_count_if_empty.md @@ -0,0 +1,13 @@ +# META +~~~ini +description=List.count_if on empty list returns 0 +type=repl +~~~ +# SOURCE +~~~roc +» List.count_if([], |x| x > 2) +~~~ +# OUTPUT +0 +# PROBLEMS +NIL diff --git a/test/snapshots/repl/list_count_if_none_match.md b/test/snapshots/repl/list_count_if_none_match.md new file mode 100644 index 00000000000..875be69bce1 --- /dev/null +++ b/test/snapshots/repl/list_count_if_none_match.md @@ -0,0 +1,13 @@ +# META +~~~ini +description=List.count_if returns 0 when no elements match +type=repl +~~~ +# SOURCE +~~~roc +» List.count_if([1, 2, 3], |x| x > 10) +~~~ +# OUTPUT +0 +# PROBLEMS +NIL