From 92e958b654a80657aa646aabd0f3bdc4e5c79940 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 22 Jun 2014 23:15:53 +0200 Subject: Add keepIf proc and keepIfIt template to sequtils --- lib/pure/collections/sequtils.nim | 49 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index f5db9d3fa..8e50b9e20 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -182,6 +182,24 @@ proc filter*[T](seq1: seq[T], pred: proc(item: T): bool {.closure.}): seq[T] = ## assert f2 == @["yellow"] accumulateResult(filter(seq1, pred)) +proc keepIf*[T](seq1: var seq[T], pred: proc(item: T): bool {.closure.}) = + ## Keeps the items in the passed sequence if they fulfilled the predicate. + ## Same as the ``filter`` proc, but modifies the sequence directly. + ## + ## Example: + ## + ## .. code-block:: nimrod + ## var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1] + ## filter(floats, proc(x: float): bool = x > 10) + ## assert floats == @[13.0, 12.5, 10.1] + var pos = 0 + for i in 0 .. 10) + assert floats == @[13.0, 12.5, 10.1] + block: # filterIt test let temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44] @@ -426,6 +470,11 @@ when isMainModule: assert acceptable == @[-2.0, 24.5, 44.31] assert notAcceptable == @[-272.15, 99.9, -113.44] + block: # keepIfIt test + var candidates = @["foo", "bar", "baz", "foobar"] + keepIfIt(candidates, it.len == 3 and it[0] == 'b') + assert candidates == @["bar", "baz"] + block: # toSeq test let numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9] -- cgit 1.4.1-2-gfad0 From f6c4864f9fe2c4b8fdd874c4f55c2c38c36d476f Mon Sep 17 00:00:00 2001 From: def Date: Sat, 28 Jun 2014 14:38:48 +0200 Subject: Rename keepIfIt to keepItIf --- lib/pure/collections/sequtils.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 8e50b9e20..27e02a5db 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -270,16 +270,16 @@ template filterIt*(seq1, pred: expr): expr {.immediate.} = if pred: result.add(it) result -template keepIfIt*(varSeq, pred: expr) = +template keepItIf*(varSeq, pred: expr) = ## Convenience template around the ``keepIf`` proc to reduce typing. ## ## Unlike the `proc` version, the predicate needs to be an expression using - ## the ``it`` variable for testing, like: ``keepIfIt("abcxyz", it == 'x')``. + ## the ``it`` variable for testing, like: ``keepItIf("abcxyz", it == 'x')``. ## Example: ## ## .. code-block:: nimrod ## var candidates = @["foo", "bar", "baz", "foobar"] - ## keepIfIt(candidates, it.len == 3 and it[0] == 'b') + ## keepItIf(candidates, it.len == 3 and it[0] == 'b') ## assert candidates == @["bar", "baz"] var pos = 0 for i in 0 ..