|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
Finite and infinite iteratorsAn iterator can be finite or infinite. Let's see an example for each. Finite iteratoriterator down(n: Positive): int = ## Iterate down to 0 (incl.). var n: int = n while n >= 0: yield n dec n proc main() = for n in down(3): echo n main() Output: 3 2 1 0 Infinite iteratorAn infinite iterator would never stop generating values. So you must pay attention on the caller side to stop the iteration (with a iterator up(n: int): int = ## Iterate up from `n` (incl.). var n = n while true: yield n inc n proc main() = var cnt = 0 for n in up(10): echo n cnt += 1 if cnt >= 5: break # # main() Output: 10 11 12 13 14 Here we print just the first five elements and then we stop. |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |