Last active
December 29, 2015 00:39
-
-
Save Varriount/7587953 to your computer and use it in GitHub Desktop.
Generics vs Typedesc : The Movie
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
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The correct way to define an iterator like count is this: