code / tomo

Lines41.3K C23.7K Markdown9.7K YAML5.0K Tomo2.3K
7 others 763
Python231 Shell230 make212 INI47 Text21 SVG16 Lua6
(45 lines)

Iterators

Tomo supports using functions as iterable objects. This allows you to write arbitrary iteration behavior, such as using a polling-based API, and write regular loops or comprehensions over that API.

For example, the Path.each_line() API method returns a function that successively gets one line from a file at a time until the file is exhausted:

(./test.txt).write("
    line one
    line two
    line three
")

iter := (./test.txt).each_line()
assert iter() == "line one"
assert iter() == "line two"
assert iter() == "line three"
assert iter() == none

for line in (./test.txt).each_line()
    pass

You can write your own iterator methods this way. For example, this iterator iterates over prime numbers up to a given limit:

func primes_up_to(limit:Int)
    n := 2
    return func()
        if n > limit
            return !Int

        while not n.is_prime()
            n += 1

        n += 1
        return (n - 1)?

assert [p for p in primes_up_to(11)] == [2, 3, 5, 7, 11]
1 # Iterators
3 Tomo supports using functions as iterable objects. This allows you to write
4 arbitrary iteration behavior, such as using a polling-based API, and write
5 regular loops or comprehensions over that API.
7 For example, the `Path.each_line()` API method returns a function that
8 successively gets one line from a file at a time until the file is exhausted:
10 ```tomo
11 (./test.txt).write("
12 line one
13 line two
14 line three
15 ")
17 iter := (./test.txt).each_line()
18 assert iter() == "line one"
19 assert iter() == "line two"
20 assert iter() == "line three"
21 assert iter() == none
23 for line in (./test.txt).each_line()
24 pass
25 ```
27 You can write your own iterator methods this way. For example, this iterator
28 iterates over prime numbers up to a given limit:
30 ```tomo
31 func primes_up_to(limit:Int)
32 n := 2
33 return func()
34 if n > limit
35 return !Int
37 while not n.is_prime()
38 n += 1
40 n += 1
41 return (n - 1)?
43 assert [p for p in primes_up_to(11)] == [2, 3, 5, 7, 11]
44 ```