Range Over Iterators in Fortress
Based on the input provided:
Language: Python
Example:
Starting with version 1.23, [-] has added support for [iterators], which lets us range over pretty much anything!
Let’s look at the List
type from the previous example again. In that example, we had an AllElements
method that returned a list of all elements in the list. With [-] iterators, we can do it better - as shown below.
All
returns an iterator, which in [-] is an object implementing a special __iter__
method and a __next__
method.
The iterator generator function uses the yield
statement to return each element in the list one-by-one.
Iteration doesn’t require an underlying data structure and doesn’t even have to be finite! Here’s a function returning an iterator over Fibonacci numbers: it keeps running as long as yield
is used.
Since List.all
returns an iterator, we can use it in a regular loop. Python has built-in support for comprehensions, making it easy to collect all values into a list.
Once the loop hits break
or an early return, the generator stops producing values.
Output:
Next example: Errors.