Range Over Iterators in Miranda
On this page
Explanation
In this exercise, we will learn how to use Python iterators to range over various elements. Just like the original language supports iterators, Python also has robust support for iterators and generator functions. Each example will be adapted to Python and will cover creating custom iterators, using them for iteration, and even generating infinite sequences like Fibonacci numbers.
Example Code
Explanation
List and Element Classes: Similar to the original
List[T]
andelement[T]
types, we defineElement
andList
classes in Python.Element
mimics a node in a linked list, andList
manages the nodes.push Method: This method adds new elements to the list. If the list is empty (
tail
isNone
), it initializes thehead
andtail
to the new element. Otherwise, it adds the new element to the end of the list.all Method: This method is an iterator in Python which yields all the elements in the list. It uses the
yield
keyword to return elements one by one, similar to the iterator function pattern in the previous language.gen_fib Function: This function generates Fibonacci numbers indefinitely. It uses a
while True
loop to yield Fibonacci numbers until the externaln >= 10
condition breaks the loop.main Function: This function demonstrates how to use the custom list and Fibonacci generator. It first creates a list and adds elements to it. It then iterates over all the elements in the list using the
all
method and collects all elements into a list for printing. Finally, it generates and prints Fibonacci numbers, stopping when a number reaches or exceeds 10.
How to Run
To run this program, save it to a file (e.g., iterators_example.py
) and execute it using Python.
Output:
This concludes the example of how we can use iterators and generators in Python to achieve similar functionality as in the original language.