I'm trying to learn Nim by translating existing Python code and one area I got stuck is to come up with simple coroutines. In Python, you can send back a value to the generator which can receive the value from yield statement. I found Nim has coro standard module for coroutines, but I'd be more interested in much simpler solutions to accomplish something like an example below. Any suggestions?
def counter (maximum):
i = 0
while i < maximum:
val = (yield i)
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
>>> it = counter(10)
>>> print it.next()
0
>>> print it.next()
1
>>> print it.send(8)
8
>>> print it.next()
9
>>> print it.next()
Traceback (most recent call last):
File ``t.py'', line 15, in ?
print it.next()
StopIteration
from https://docs.python.org/2.5/whatsnew/pep-342.htmlRead about iterator in manual
proc countTo(maxi: int): iterator(x = 1): int =
result = iterator(x = 1): int =
var i = 0
while i <= maxi:
i.inc x
yield i
var itx3 = countTo 3
echo itx3(2)
if not itx3.finished:
echo itx3()