Skip to content

Instantly share code, notes, and snippets.

@klaufir
Created June 5, 2014 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klaufir/b2a8d13bf1f6f5296dc6 to your computer and use it in GitHub Desktop.
Save klaufir/b2a8d13bf1f6f5296dc6 to your computer and use it in GitHub Desktop.
iterator imap[T,O](iter: iterator(): T {.closure.}, transform_elem: proc(e:T):O): O {.closure.} =
var iterInst = iter
for x in iterInst():
yield transform_elem(x)
iterator ifilter[T](iter: iterator(): T {.closure.}, filter: proc(e:T):bool): T {.closure.} =
var iterInst = iter
for x in iterInst():
if filter(x):
yield x
proc ifold[T](iter: iterator(): T {.closure.}, f : proc(a:T, b:T):T, initval : T ):T =
var iterInst = iter
result = initval
for x in iterInst():
result = f(result, x)
# usage:
# only works on closure iterators
iterator it(): int {.closure.} =
for y in countup(1,10):
yield y
echo "-----------"
for z in it.imap(proc(x:int):int = x*x):
echo z
echo "-----------"
for z in it.ifilter(proc(x:int):bool = x > 4):
echo z
echo "-----------"
echo it.ifold(proc(a,b:int):int = a+b, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment