Skip to content

Commit

Permalink
feat: adding list:countIf
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperFola committed Oct 30, 2024
1 parent 5d8bf07 commit 09bffc9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
23 changes: 22 additions & 1 deletion List.ark
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@

# @brief Check if a condition if verified for one or more elements of a list
# @param _L the list to work on
# @param _f the conditon
# @param _f the condition
# =begin
# (let a [1 2 3 4])
# (let f (fun (e) (< e 3)))
Expand All @@ -335,3 +335,24 @@
(set _verified true))
(set _index (+ 1 _index)) })
_verified }))

# @brief Count the number of elements in a list that match a condition
# @param _L the list to work on
# @param _f the condition
# =begin
# (let lst [1 2 3 4 5 6 7 8 9])
# (let is_even (fun (e) (= 0 (mod e 2))))
# (print (count_if lst is_even)) # 4
# =end
# @author https://github.com/SuperFola
(let list:countIf (fun (_L _f) {
(let _inner (fun (lst cond acc)
(if (not (empty? lst))
(_inner
(tail lst)
cond
(if (cond (head lst))
(+ 1 acc)
acc))
acc)))
(_inner _L _f 0) }))
6 changes: 5 additions & 1 deletion tests/list-tests.ark
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,8 @@
(test:expect (list:forAll [] (fun (e) (= e 2))))
(test:expect (list:any a (fun (e) (< e 2))))
(test:expect (not (list:any a (fun (e) (> e 8)))))
(test:expect (not (list:any [] (fun (e) (= e 8)))))})
(test:expect (not (list:any [] (fun (e) (= e 8)))))

(test:eq (list:countIf a (fun (e) (= 0 (mod e 2)))) 1)
(test:eq (list:countIf a (fun (e) (= 1 (mod e 2)))) 2)
(test:eq (list:countIf [] (fun (e) (= 1 (mod e 2)))) 0)})

0 comments on commit 09bffc9

Please sign in to comment.