Skip to content

Instantly share code, notes, and snippets.

@Varriount
Created February 10, 2014 21:58
Show Gist options
  • Save Varriount/8925071 to your computer and use it in GitHub Desktop.
Save Varriount/8925071 to your computer and use it in GitHub Desktop.
type filterProc[T] = proc (value:T): bool {.closure.}
iterator dropWhile* [iT, rT](predicate: filterProc[rT], iter: iT): rT =
## An iterator that drops (skips) elements from the iterable as long as the
## predicate is true; afterwards, returns every element.
## Note, this version of the iterator does not produce any output until
## the predicate first becomes false, so it may have a lengthy start-up time.
var
broken = false
element: rT
while not finished(iter):
element = iter() # This will only work with iterables that take no args.
if not broken and not predicate(element):
broken = false
yield element
when isMainModule:
block:
iterator testIter: int =
for i in 0..10:
yield i
proc predProc(element: int): bool =
result = (element == 5)
var
dwResult = @[5,6,7,8,9,10]
var dwOutput = newSeq[int]()
for i in dropWhile[type(testIter), int](predProc, testIter):
dwOutput.add(i)
assert(dwOutput == dwResult)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment