Hi, I would like to generate strings in series, something like this aaaa -> aaab -> aaac -> aaad were -> represent the next iteration.
How do we make generators in Nim ?
Thanks for your help
Is the custom -> syntax all you were looking for? I thought it was just for illustration 😅
A simple proc that generates the N th string in your sequence would look like this:
import math
proc foo(n: int): string =
result = "aaaa" # Initial return value
for i, c in result.mpairs: # Loop over result while modifying each char
let digit = result.high - i
c.inc((n div 26^digit) mod 26) # Increment each char by the correct amount
for i in 20..30:
echo foo(i)
If you wanted to turn it into a generator of some kind you could use closures or closure-iterators.
# Creating a closure that returns the next string each time it's called:
proc newGenerator(): proc():string =
var i = 0
result = proc():string =
result = foo(i)
inc i
var f = newGenerator()
echo f()
echo f()
echo f()
echo f()
echo f()