diff options
author | narimiran <miran.tuhtan+git@gmail.com> | 2017-10-21 20:32:10 +0200 |
---|---|---|
committer | narimiran <miran.tuhtan+git@gmail.com> | 2017-10-21 20:32:10 +0200 |
commit | a897693395f6a7c0457133501fe9b30d975f1903 (patch) | |
tree | 2d65aca2c531bf006e517c96eca983c3a12ec1d6 /lib | |
parent | aa96343f1dd7e78c43fe7a4e7761e05dba2b4411 (diff) | |
download | Nim-a897693395f6a7c0457133501fe9b30d975f1903.tar.gz |
add `count` to sequtils
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pure/collections/sequtils.nim | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index e8e725aa3..3e49d0982 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -43,6 +43,20 @@ proc concat*[T](seqs: varargs[seq[T]]): seq[T] = result[i] = itm inc(i) +proc count*[T](s: seq[T], x: T): int = + ## Count the occurrences of the item `x` in the sequence `s`. + ## + ## Example: + ## + ## .. code-block:: + ## let + ## s = @[1, 2, 2, 3, 2, 4, 2] + ## c = count(s, 2) + ## assert c == 4 + for itm in items(s): + if itm == x: + inc result + proc cycle*[T](s: seq[T], n: Natural): seq[T] = ## Returns a new sequence with the items of `s` repeated `n` times. ## @@ -674,6 +688,23 @@ when isMainModule: total = concat(s1, s2, s3) assert total == @[1, 2, 3, 4, 5, 6, 7] + block: # count test + let + s1 = @[1, 2, 3, 2] + s2 = @['a', 'b', 'x', 'a'] + r0 = count(s1, 0) + r1 = count(s1, 1) + r2 = count(s1, 2) + r3 = count(s2, 'y') + r4 = count(s2, 'x') + r5 = count(s2, 'a') + assert r0 == 0 + assert r1 == 1 + assert r2 == 2 + assert r3 == 0 + assert r4 == 1 + assert r5 == 2 + block: # duplicates test let dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4] |