Skip to content

Instantly share code, notes, and snippets.

@zah
Created April 22, 2018 11:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zah/f5d9238d0f7e6f0ed37364a95f311b2b to your computer and use it in GitHub Desktop.
Save zah/f5d9238d0f7e6f0ed37364a95f311b2b to your computer and use it in GitHub Desktop.
# These two are semantically equivalent:
proc makeIterator(x, y: int): Irerator[int] =
result = iterator(): int {.closure.} =
yield 1
yield 2
iterator makeIterator(x, y): int =
yield 1
yield 2
# both of them can be passed to `sumValues`
proc sumValues(list: Iterator[int]): int =
for e in list: result += e
# now this is different:
proc makeFancyIterator(x, y: int): iterator(s: string): int =
result = iterator(s: string): int {.closure.} =
yield x + s.len
yeild y + s.len
# it has to be used like this:
var iter = makeFancyIterator(3, 5)
echo iter("test") # some(7), because x = 3 and s.len = 4
echo iter("a") # some(6), because y = 5 and s.len = 1
echo iter("more") # none(), because the iteration has finished
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment