Range Over Iterators in R Programming Language

Our first program demonstrates how to iterate over a custom list and generate Fibonacci sequences using iterators. Here’s the full source code translated to Python:

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

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

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

    def all(self):
        current = self.head
        def iterator():
            nonlocal current
            while current is not None:
                yield current.val
                current = current.next
        return iterator()

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

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

# Iterating over the list elements using the custom iterator
    for e in lst.all():
        print(e)

# Collecting all elements into a list
    all_elements = list(lst.all())
    print("all:", all_elements)

# Generating Fibonacci numbers and iterating over them
    fib_iterator = gen_fib()
    for n in fib_iterator:
        if n >= 10:
            break
        print(n)

if __name__ == "__main__":
    main()

To run this Python code, simply execute it as a script.

Explanation:

  1. Element Class: This defines the structure of an element in the list, containing a value and a pointer/reference to the next element.

  2. List Class: This class manages the linked list and provides methods to add (push) and iterate over all elements (all).

  3. gen_fib Function: This function generates an infinite sequence of Fibonacci numbers, which can be iterated until a specific condition is met (e.g., values less than 10).

  4. main Function:

    • Creates a list and pushes some elements into it.
    • Iterates over the list elements and prints each one.
    • Collects all elements of the list into a Python list and prints them.
    • Generates Fibonacci numbers and prints them until a value reaches 10.

This translated Python version makes use of Python’s generator functions (yield) to replicate the iterator behavior.