Created
February 9, 2014 05:50
-
-
Save Varriount/8894927 to your computer and use it in GitHub Desktop.
Portion of Itertools module
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
| iterator cycle*[iterT, returnT](iter: iterT): returnT = | |
| ## An iterator returning elements from the iterable and saving a | |
| ## copy of each. When the iterable is exhausted, return elements | |
| ## from the saved copy. Repeats indefinitely. | |
| ## | |
| ## Parameters: | |
| ## iter: The iterator to cycle through | |
| var cont: seq[returnT] = @[] | |
| for element in iter: | |
| yield element | |
| cont.add(element) | |
| while True: | |
| for element in cont: | |
| yield element | |
| when isMainModule: | |
| block: | |
| var | |
| cycleSeq = @[1,2] | |
| emptySeq = newSeq[int]() | |
| cycleIterator: cycle[seq[int], int] | |
| for i in 1..3: | |
| emptySeq.add(cycleIterator(cycleSeq)) | |
| assert(emptySeq == @[1,2,1,2,1,2]) | |
| echo(repr(emptySeq)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment