From a897693395f6a7c0457133501fe9b30d975f1903 Mon Sep 17 00:00:00 2001 From: narimiran Date: Sat, 21 Oct 2017 20:32:10 +0200 Subject: add `count` to sequtils --- lib/pure/collections/sequtils.nim | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'lib/pure/collections') 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] -- cgit 1.4.1-2-gfad0 From ea752f29a0fd03552d49b1473b52de91b148765e Mon Sep 17 00:00:00 2001 From: narimiran Date: Sun, 22 Oct 2017 13:43:45 +0200 Subject: more descriptive names --- lib/pure/collections/sequtils.nim | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/pure/collections') diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 3e49d0982..0cc367fa7 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -43,8 +43,8 @@ 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`. +proc count*[T](list: seq[T], item: T): int = + ## Count the occurrences of the item `item` in the sequence `list`. ## ## Example: ## @@ -53,8 +53,8 @@ proc count*[T](s: seq[T], x: T): int = ## s = @[1, 2, 2, 3, 2, 4, 2] ## c = count(s, 2) ## assert c == 4 - for itm in items(s): - if itm == x: + for x in items(list): + if x == item: inc result proc cycle*[T](s: seq[T], n: Natural): seq[T] = -- cgit 1.4.1-2-gfad0