diff options
author | Grzegorz Adam Hankiewicz <gradha@imap.cc> | 2014-02-02 08:47:42 -0800 |
---|---|---|
committer | Grzegorz Adam Hankiewicz <gradha@imap.cc> | 2014-02-02 08:47:42 -0800 |
commit | ea42682dbccba52d4e5905ce473128422c0ffe98 (patch) | |
tree | d5f4d39e6c0b50e5dfd851527e23778ecb8d06c1 | |
parent | c30f6cfcf11cf5e61d708db476d7a6fcb62aab23 (diff) | |
parent | 700f32e81470c16ff65bc83d256ad1368f05e4ad (diff) | |
download | Nim-ea42682dbccba52d4e5905ce473128422c0ffe98.tar.gz |
Merge pull request #846 from gradha/pr_adds_mapit_templates
Adds convenience mapIt templates to sequtils.
-rw-r--r-- | lib/pure/collections/sequtils.nim | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 3993f1ccc..b2f72ee14 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -276,6 +276,38 @@ template foldr*(sequence, operation: expr): expr = result = operation result +template mapIt*(seq1, typ, pred: expr): expr = + ## Convenience template around the ``map`` proc to reduce typing. + ## + ## The template injects the ``it`` variable which you can use directly in an + ## expression. You also need to pass as `typ` the type of the expression, + ## since the new returned sequence can have a different type than the + ## original. Example: + ## + ## .. code-block:: nimrod + ## let + ## nums = @[1, 2, 3, 4] + ## strings = nums.mapIt(string, $(4 * it)) + var result {.gensym.}: seq[typ] = @[] + for it {.inject.} in items(seq1): + result.add(pred) + result + +template mapIt*(varSeq, pred: expr) = + ## Convenience template around the mutable ``map`` proc to reduce typing. + ## + ## The template injects the ``it`` variable which you can use directly in an + ## expression. The expression has to return the same type as the sequence you + ## are mutating. Example: + ## + ## .. code-block:: nimrod + ## var nums = @[1, 2, 3, 4] + ## nums.mapIt(it * 3) + ## assert nums[0] + nums[3] == 15 + for i in 0 .. <len(varSeq): + let it {.inject.} = varSeq[i] + varSeq[i] = pred + when isMainModule: import strutils block: # concat test @@ -381,4 +413,11 @@ when isMainModule: Inserting [2,2,2,2,2,2] into [1,1,1,1,1,1,1,1] at 3 is [1,1,1,2,2,2,2,2,2,1,1,1,1,1]""" + block: # mapIt tests + var + nums = @[1, 2, 3, 4] + strings = nums.mapIt(string, $(4 * it)) + nums.mapIt(it * 3) + assert nums[0] + nums[3] == 15 + echo "Finished doc tests" |