diff options
| author | Bruce Hill <bruce@bruce-hill.com> | 2024-09-11 22:38:13 -0400 |
|---|---|---|
| committer | Bruce Hill <bruce@bruce-hill.com> | 2024-09-11 22:38:13 -0400 |
| commit | 62408e4efcfac85d4c835242391aae761c2313eb (patch) | |
| tree | 951fa71f9ae0d9b59566f8466e5ece73edd5e6fa | |
| parent | 3443edf760bd4d53aafb2079f7ab67d98ee5013e (diff) | |
Document iterators
| -rw-r--r-- | docs/iterators.md | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/docs/iterators.md b/docs/iterators.md new file mode 100644 index 00000000..63a44fcf --- /dev/null +++ b/docs/iterators.md @@ -0,0 +1,50 @@ +# 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: + +```tomo +(./test.txt):write(" + line one + line two + line three +") + +>> iter := (./test.txt):each_line() +>> iter() += "line one"? +>> iter() += "line two"? +>> iter() += "line three"? +>> iter() += !Text + +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: + +```tomo +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)? + +>> [p for p in primes_up_to(11)] += [2, 3, 5, 7, 11] +``` + |
