Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ◇C++, ◇Clojure, ◇Scala


[ edit | logout ]
[ sandbox | passwd ]

Python's generator-like iterator

Python has generators. yield pauses, the state is frozen, and the next call resumes. Let's see how to do it in Nim.

Python vs Nim
def counter(start):
    i = start
    while True:
        yield i
        i += 1

a = counter(0)
b = counter(100)

print(next(a))  # 0
print(next(a))  # 1
print(next(b))  # 100
print(next(a))  # 2
print(next(b))  # 101
proc counter(start: int): iterator(): int =
  return iterator(): int =
    var i = start
    while true:
      yield i
      inc i

let a = counter(0)
let b = counter(100)

echo a()   # 0
echo a()   # 1
echo b()   # 100
echo a()   # 2
echo b()   # 101

a and b are independent, each remembers its own i.

In Nim we use the following pattern: we wrap the iterator in a factory proc that captures the parameters and returns an anonymous iterator. The proc captures the start parameter, and each call to counter() creates a fresh independent instance.

More info here.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 May 07, 20:11