Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can countup and countdown iterators in Nim language be used in variable declaration?

Tags:

nim-lang

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 do not works:

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: attempting to call undeclared routine: 'countup'

How countup is undeclared routine , where it is a built-in iterator !?

Or it is a bug to report about ?

What are the solutions to enforce a custom iterator in variable declaration, such countup or countdown ?

NOTE: I am using Nim 0.13.0 on Windows platform.

like image 629
GeoObserver Avatar asked Feb 29 '16 10:02

GeoObserver


1 Answers

That happens because countup is an inline iterator only. There is a definition for .. as an inline iterator as well as a Slice:

  • http://nim-lang.org/docs/system.html#...i,S,T
  • http://nim-lang.org/docs/system.html#..,T,T

Inline iterators are 0-cost abstractions. Instead you could use a first-class closure iterator by converting the inline iterator to one:

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
like image 100
def- Avatar answered Nov 15 '22 09:11

def-