summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorDominik Picheta <dominikpicheta@googlemail.com>2017-10-22 13:03:16 +0100
committerGitHub <noreply@github.com>2017-10-22 13:03:16 +0100
commit427fe47e5e3bf38d04cfa7223475c498c5fb4dc7 (patch)
tree66f1171d3f6dd9485f17130000b688a0dcc24f79 /lib
parenta5a305a7fbb2d53b7ce19be759cffa5a371af169 (diff)
parentea752f29a0fd03552d49b1473b52de91b148765e (diff)
downloadNim-427fe47e5e3bf38d04cfa7223475c498c5fb4dc7.tar.gz
Merge pull request #6558 from narimiran/seqCount
add `count` to sequtils
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/collections/sequtils.nim31
1 files changed, 31 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim
index e8e725aa3..0cc367fa7 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](list: seq[T], item: T): int =
+  ## Count the occurrences of the item `item` in the sequence `list`.
+  ##
+  ## Example:
+  ##
+  ## .. code-block::
+  ##   let
+  ##     s = @[1, 2, 2, 3, 2, 4, 2]
+  ##     c = count(s, 2)
+  ##   assert c == 4
+  for x in items(list):
+    if x == item:
+      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]