Created
April 22, 2018 11:41
-
-
Save zah/f5d9238d0f7e6f0ed37364a95f311b2b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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