Skip to content

Commit 09bffc9

Browse files
committed
feat: adding list:countIf
1 parent 5d8bf07 commit 09bffc9

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

List.ark

+22-1
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@
319319

320320
# @brief Check if a condition if verified for one or more elements of a list
321321
# @param _L the list to work on
322-
# @param _f the conditon
322+
# @param _f the condition
323323
# =begin
324324
# (let a [1 2 3 4])
325325
# (let f (fun (e) (< e 3)))
@@ -335,3 +335,24 @@
335335
(set _verified true))
336336
(set _index (+ 1 _index)) })
337337
_verified }))
338+
339+
# @brief Count the number of elements in a list that match a condition
340+
# @param _L the list to work on
341+
# @param _f the condition
342+
# =begin
343+
# (let lst [1 2 3 4 5 6 7 8 9])
344+
# (let is_even (fun (e) (= 0 (mod e 2))))
345+
# (print (count_if lst is_even)) # 4
346+
# =end
347+
# @author https://github.com/SuperFola
348+
(let list:countIf (fun (_L _f) {
349+
(let _inner (fun (lst cond acc)
350+
(if (not (empty? lst))
351+
(_inner
352+
(tail lst)
353+
cond
354+
(if (cond (head lst))
355+
(+ 1 acc)
356+
acc))
357+
acc)))
358+
(_inner _L _f 0) }))

tests/list-tests.ark

+5-1
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,8 @@
6969
(test:expect (list:forAll [] (fun (e) (= e 2))))
7070
(test:expect (list:any a (fun (e) (< e 2))))
7171
(test:expect (not (list:any a (fun (e) (> e 8)))))
72-
(test:expect (not (list:any [] (fun (e) (= e 8)))))})
72+
(test:expect (not (list:any [] (fun (e) (= e 8)))))
73+
74+
(test:eq (list:countIf a (fun (e) (= 0 (mod e 2)))) 1)
75+
(test:eq (list:countIf a (fun (e) (= 1 (mod e 2)))) 2)
76+
(test:eq (list:countIf [] (fun (e) (= 1 (mod e 2)))) 0)})

0 commit comments

Comments
 (0)