Range Over Iterators in Karel
Our example demonstrates how to iterate over elements using functions that act like iterators. This is typically done using features like generators in the specified language: Python.
Here’s how we could perform similar operations in Python:
Explanation:
List and Element classes: Here we define the
List
andElement
classes.List
keeps references to the head and tail of the list.Element
keeps the value and the reference to the next element.Push method: The
push
function adds elements to the list. It checks if the tail isNone
(list is empty), it initializes the head and tail, otherwise, it appends the new element to the end of the list.All Elements method: The
all_elements
function is a generator in Python that yields each element’s value from the list.Fibonacci generator: The
gen_fib
function is a generator that yields Fibonacci numbers indefinitely, similar to iterators in the initial language.Main function: The
main
function demonstrates how to create a list, push elements into it, and iterate over its elements. It also shows how to generate and iterate over Fibonacci numbers, stopping the iteration when a number greater than or equal to 10 is found.