Iterator chaining: Lazy Evaluation

With Coconut's iterator chaining and slicing also comes the idea of lazy evaluation. This is the idea that nothing is evaluated until it is needed. Take a look at the following function definition:

def x(n) = (n,) :: x(n + 1)
This is an instruction to create an infinite sequence starting with the input provided. However, if used properly in Coconut, such a function will not lead you into an infinite loop. Try defining this function and entering the following command into Coconut:

x(5)$[0:5] |> list |> print
The command instructs Coconut to create the iterator for a sequence starting at 5. It then uses the iterator slicing functionality to take the first 5 elements to be iterated over, converts them to a list and prints them. Since the evaluation was lazy, Coconut did not have to go into an infinite loop to define the entire iterator, and instead only dealt with the part we explicitly asked it for.

If we were to try to use lazy evaluation in this way in Python, it would be incredibly complicated, and it would require you to understand iterators and their functionality in Python on a very deep level. If you would like to get an idea for what this would look like, simply copy that one-line function definition above into a Coconut file and compile it to Python.

To see a more complex implementation of chaining in coconut, look at Lazy Lists!


Next
Previous