Is it possible to use counting and countdown iterators in Nim in variable declarations?

I am trying to learn Nim and its features, such Iterators; and I found that the following example works fine.

for i in countup(1,10):   # Or its equivalent 'for i in 1..10:' 
 echo($i)

However, the following does not work:

var 
 counter = countup(1,10) # THIS DO NOT WORK !
 # counter = 1..10   # This works

for i in counter :  
 echo($i)

The Nim compiler reports the following error:

Error: attempt to call undeclared procedure: "countup"

How is an undeclared procedure counted, where is the built-in iterator !?

Or is this a bug that needs to be reported?

What are the solutions for enforcing a custom iterator in a variable declaration, such a count, or a countdown?

NOTE. I am using Nim 0.13.0 on a Windows platform.

+3
source share
2 answers

, countup . .. , Slice:

Inline- - 0-cost. , :

template toClosure*(i): auto =
  ## Wrap an inline iterator in a first-class closure iterator.
  iterator j: type(i) {.closure.} =
    for x in i:
      yield x
  j

var counter = toClosure(countup(1,10))

for i in counter():
  echo i
+4

. toSeq sequtils.

    import sequtils
    let x = toSeq(1..5)
    let y = toSeq(countdown(5, 1))

, accumulateResult ( )

    proc countup(a, b: int, step = 1): seq[int] =
      accumulateResult(countup(a, b, step))

    let x = countup(1, 5)
0

All Articles