We discussed in the iterators lesson how Python iterators relate to Haskell lists. If you’re familiar with the
itertools module, these next few lessons are to help you get started quickly with Haskell’s
Data.List module. We will also discuss a few of Python’s built-in functions. Python built-in functions All of the functions that we discuss here return iterators.
In all of the Python code examples, we assume that everything from
itertools is imported:
We’ll start by introducing
itertools.islice because we’ll need to use
islice to demonstrate some of the other
The primary use of
islice is to hack an iterator down to some fixed length.
This is particularly important because some iterators never stop.
So when we want to print the contents of an iterator we’ll often need to print just some small chunk of its beginning.
The equivalent Haskell function is
take is defined in the
Data.List module in the
base package, and it is also in
Prelude (so it doesn’t need to be imported). This is the case for most of the Haskell functions that we discuss here.
islice is used with two arguments, the first argument is the (zero-indexed) position to start at, and the second argument is the position to stop before.
In this example, the first argument
3 signifies that we want to start at the fourth character (
d), and the second argument
5 specifies that we want to stop before the sixth character, so the last character we take is the fifth one (
Haskell does not overload functions by arity like Python does. Instead we have a separate function,
Prelude which skips some number of elements and returns the remainder of the list. By using
take together, we can achieve the same effect as the two-argument version of
We might also consider writing this using the function composition operator
The final parameter lets us take elements periodically. In this example, we take the first element (
start = 0) and every third element after that (
step = 3).
There is no direct analogue in the Haskell base package for this, so let’s think about how we might write one. We wouldn’t write this sort of function recursively in Python because it is too easy to overflow the call stack. Haskell does not suffer this same problem.
A lot of functions over lists can be expressed naturally with recursion, and this one is no exception.
- If the input list is empty, the output is empty.
- If the
0, then the first element of the input list (
x) is the first element of the output list.
- Otherwise, we skip the first element of the input list, and apply
startSteprecursively with the
startparameter reduced by one.