Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/build/roc/Builtin.roc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions test/snapshots/repl/list_count_if.md
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions test/snapshots/repl/list_count_if_all_match.md
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions test/snapshots/repl/list_count_if_empty.md
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions test/snapshots/repl/list_count_if_none_match.md
Original file line number Diff line number Diff line change
@@ -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
Loading