Skip to content

Instantly share code, notes, and snippets.

@Varriount
Created February 9, 2014 05:50
Show Gist options
  • Save Varriount/8894927 to your computer and use it in GitHub Desktop.
Save Varriount/8894927 to your computer and use it in GitHub Desktop.
Portion of Itertools module
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