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:

class List:
    def __init__(self):
        self.head = None
        self.tail = None

class Element:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def push(lst, v):
    if lst.tail is None:
        lst.head = Element(v)
        lst.tail = lst.head
    else:
        lst.tail.next = Element(v)
        lst.tail = lst.tail.next

def all_elements(lst):
    current = lst.head
    while current is not None:
        yield current.val
        current = current.next

def gen_fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

def main():
    lst = List()
    push(lst, 10)
    push(lst, 13)
    push(lst, 23)

    print("List items:")
    for e in all_elements(lst):
        print(e)

    all_vals = list(all_elements(lst))
    print("all:", all_vals)

    print("Fibonacci numbers:")
    for n in gen_fib():
        if n >= 10:
            break
        print(n)

if __name__ == '__main__':
    main()

Explanation:

  1. List and Element classes: Here we define the List and Element classes. List keeps references to the head and tail of the list. Element keeps the value and the reference to the next element.

  2. Push method: The push function adds elements to the list. It checks if the tail is None (list is empty), it initializes the head and tail, otherwise, it appends the new element to the end of the list.

  3. All Elements method: The all_elements function is a generator in Python that yields each element’s value from the list.

  4. Fibonacci generator: The gen_fib function is a generator that yields Fibonacci numbers indefinitely, similar to iterators in the initial language.

  5. 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.