Iterator-producing function in Nim: works when assigning the iterator, stuck when calling it directly

Viewed 79

I tried to make a procedure that creates an iterator, as follows:

proc makeCDFrom(start: int): iterator(): int =
  result = iterator(): int =
    var
      i: int = start
    while i >= 0:
      echo "i:", i
      yield(i)
      dec(i)

let cdFrom6 = makeCDFrom(6)
for j in cdFrom6():
  echo "j:", j

This appears to work as expected:

i:6
j:6
i:5
j:5
i:4
j:4
i:3
j:3
i:2
j:2
i:1
j:1
i:0
j:0

However, initially, I had tried with this slight variation:

proc makeCDFrom(start: int): iterator(): int =
  result = iterator(): int =
    var
      i: int = start
    while i >= 0:
      echo "i:", i
      yield(i)
      dec(i)

# Note the direct call:
for j in makeCDFrom(6)():
  echo "j:", j

When I try to run the above on https://play.nim-lang.org/, it appears to be stuck. Nothing gets displayed.

Why this difference?

2 Answers

Why?

Because there's a bug.

What can you do about it?

Report the bug to github.com/nim-lang/Nim

And in the meantime use either

let myClosureIter = makeCDFrom(6)

or define your iterator without the factory:

iterator makeCDFrom(start: int): int =
    var
      i: int = start
    while i >= 0:
      echo "i:", i
      yield(i)
      dec(i)

# Note the direct call:
for j in makeCDFrom(6):
  echo "j:", j

With a slight change:

proc makeCDFrom(start: int): iterator(): int =
  echo "called again"
  result = iterator(): int =
    var
      i: int = start
    while i >= 0:
      echo "i:", i
      yield(i)
      dec(i)

And running locally, it's in an infinite loop:

called again
i:6
called again
j:6
called again
i:6
called again
j:6
called again
i:6
...
Related