Range Over Iterators in Prolog
Based on the language specified in the prolog and the provided code example, here is the translated content:
Python Code Example
Starting with version 1.23, Go 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 slice of all elements in the list. With Go iterators, we can do it better - as shown below.
class Element:
def __init__(self, val, 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(v)
if not self.tail:
self.head = new_element
self.tail = new_element
else:
self.tail.next = new_element
self.tail = new_element
def all(self):
def iterator():
current = self.head
while current:
yield current.val
current = current.next
return iterator
# Example use
lst = List()
lst.push(10)
lst.push(13)
lst.push(23)
for e in lst.all()():
print(e)
All returns an iterator function in Python. 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
keeps returning values.
def gen_fib():
a, b = 1, 1
while True:
yield a
a, b = b, a + b
# Example use
fib_iterator = gen_fib()
for n in fib_iterator:
if n >= 10:
break
print(n)
Since List.all
returns an iterator, we can use it in a regular for
loop.
Packages like itertools have a number of useful functions to work with iterators. For example, list
takes any iterator and collects all its values into a list.
all_elements = list(lst.all()())
print("all:", all_elements)
Once the loop hits break
or an early return, the iterator will stop yielding values.
Now that we can run and build basic Python programs, let’s learn more about the language.
for n in gen_fib():
if n >= 10:
break
print(n)
Expected Output
10
13
23
all: [10, 13, 23]
1
1
2
3
5
8