Skip to content

Instantly share code, notes, and snippets.

@fowlmouth
Created May 31, 2015 14:27
Show Gist options
  • Save fowlmouth/3041f72efa37bea27d1b to your computer and use it in GitHub Desktop.
Save fowlmouth/3041f72efa37bea27d1b to your computer and use it in GitHub Desktop.
proc initT (some: var string) = some = newStringOfCap(64)
proc initT [T] (some: var seq[T]) = newSeq[T](some, 0)
template filterIt*(seq1, pred: expr): expr {.immediate.} =
## Returns a new sequence with all the items that fulfilled the predicate.
##
## Unlike the `proc` version, the predicate needs to be an expression using
## the ``it`` variable for testing, like: ``filterIt("abcxyz", it == 'x')``.
## Example:
##
## .. code-block::
## let
## temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
## acceptable = filterIt(temperatures, it < 50 and it > -10)
## notAcceptable = filterIt(temperatures, it > 50 or it < -10)
## assert acceptable == @[-2.0, 24.5, 44.31]
## assert notAcceptable == @[-272.15, 99.9, -113.44]
bind initT
var result {.gensym.}: type(seq1)
initT result
for it {.inject.} in items(seq1):
if pred: result.add(it)
result
var s = "abc"
echo s.filterIt(it < 'c')
var s2 = @['a','b','c']
echo s2.filterIt(it < 'c')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment