haskpy.types.linkedlist.Nil

Nil = Nil

Linked-list with “lazy” Cons

The “lazy” Cons makes it possible to construct infinite lists. For instance, an infinite list of a repeated value 42 can be constructed as:

>>> repeat(42)
Cons(42, Cons(42, Cons(42, Cons(42, Cons(42, Cons(42, ...))))))

You can use, for instance, scanl and map to create more complex infinite lists from a simple one:

>>> xs = repeat(1).scanl(lambda acc, x: acc + x)
>>> xs
Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, Cons(6, ...))))))
>>> xs.map(lambda x: x ** 2)
Cons(1, Cons(4, Cons(9, Cons(16, Cons(25, Cons(36, ...))))))

Note that this works also for very long lists:

>>> xs.drop(10000)
Cons(10001, Cons(10002, Cons(10003, Cons(10004, Cons(10005, Cons(10006, ...))))))

One can create infinite lists by using a recursive definition:

>>> xs = Cons(42, lambda: xs)

But beware that this kind of recursive definition doesn’t always work as one might expect. For instance, the following construction causes huge recursion depths:

>>> xs = Cons(1, lambda: xs.map(lambda y: y + 1))
>>> xs
Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, Nil)))))
>>> xs.drop(10000)
RecursionError: maximum recursion depth exceeded while calling a Python object

This happens because each value depends recursively on all the previous values