Skip to content

Instantly share code, notes, and snippets.

@Varriount
Last active December 29, 2015 00:39
Show Gist options
  • Save Varriount/7587953 to your computer and use it in GitHub Desktop.
Save Varriount/7587953 to your computer and use it in GitHub Desktop.
Generics vs Typedesc : The Movie
# EXAMPLE A
iterator count* [T](start: T, step = 1): T {.closure.} =
## An iterator function that returns evenly spaced values of ordinal T,
## starting with `start`
## Note, this doesn't have any protections against overflow errors!
##
## Parameters:
## start: A starting ordinal
## step: The space between returned values.
var i = start
if step < 0:
while True:
dec(i, step)
yield i
if step > 0:
while True:
inc(i, step)
yield i
when defined(isMainModule):
block countBlock:
var intSeq = newSeq[int]()
var countIterator = count[int]
for i in 1..5:
intSeq.add(countIterator(0,5))
assert(intSeq == @[5,10,15,20,25])
echo(repr(intSeq))
# EXAMPLE B
iterator count* (T:typedesc, start: T, step = 1): T {.closure.} =
## An iterator function that returns evenly spaced values of ordinal T,
## starting with `start`
## Note, this doesn't have any protections against overflow errors!
##
## Parameters:
## start: A starting ordinal
## step: The space between returned values.
var i = start
if step < 0:
while True:
dec(i, step)
yield i
if step > 0:
while True:
inc(i, step)
yield i
when defined(isMainModule):
block countBlock:
var intSeq = newSeq[int]()
var countIterator = count(int)
for i in 1..5:
intSeq.add(countIterator(0,5))
assert(intSeq == @[5,10,15,20,25])
echo(repr(intSeq))
@zah
Copy link

zah commented Nov 21, 2013

The correct way to define an iterator like count is this:

# EXAMPLE A
proc count*[T](start: T, step = 1): auto =
  iterator counter: T {.closure.} =
    ## An iterator function that returns evenly spaced values of ordinal T,
    ## starting with `start`
    ## Note, this doesn't have any protections against overflow errors!
    ##
    ## Parameters:
    ##   start: A starting ordinal
    ##   step: The space between returned values.
    var i = start
    if step < 0:
      while True:
        dec(i, step)
        yield i
    if step > 0:
      while True:
        inc(i, step)
        yield i

  return counter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment