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

寵の児 提交于 2021-01-27 12:12:59

问题


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?


回答1:


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



回答2:


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
...


来源:https://stackoverflow.com/questions/63884552/iterator-producing-function-in-nim-works-when-assigning-the-iterator-stuck-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!