diff options
author | Dean Eigenmann <7621705+decanus@users.noreply.github.com> | 2020-04-02 12:09:29 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-02 12:09:29 +0200 |
commit | df8e0e7f0c3a2e340c625d8c55d9105da106dbfd (patch) | |
tree | b1b3adda7a75975934b08892251a0b5da12284b4 /lib/pure/collections/sequtils.nim | |
parent | d01245e501c3d90449383d055da9cb1fe5a24a7f (diff) | |
download | Nim-df8e0e7f0c3a2e340c625d8c55d9105da106dbfd.tar.gz |
feature/count (#13837)
Diffstat (limited to 'lib/pure/collections/sequtils.nim')
-rw-r--r-- | lib/pure/collections/sequtils.nim | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index e32c784c6..0cc91b0d0 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -600,6 +600,25 @@ template keepItIf*(varSeq: seq, pred: untyped) = inc(pos) setLen(varSeq, pos) +since (1, 1): + template countIt*(s, pred: untyped): Natural = + ## Returns a count of all the items that fulfilled the predicate. + ## + ## The predicate needs to be an expression using + ## the ``it`` variable for testing, like: ``countIt(@[1, 2, 3], it > 2)``. + ## + runnableExamples: + let numbers = @[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + iterator iota(n: int): int = + for i in 0..<n: yield i + assert numbers.countIt(it < 0) == 3 + assert countIt(iota(10), it < 2) == 2 + + var result = 0 + for it {.inject.} in s: + if pred: result += 1 + result + proc all*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): bool = ## Iterates through a container and checks if every item fulfills the ## predicate. |