Iteration to infinity
This lesson is about functions that produce simple never-ending iterators. The ability to represent concepts like counting upward from one and repeating an item indefinitely is a big part of what distinguishes iterators from lists in Python. In Haskell we describe things like Python iterators as “lazy” because elements are not evaluated until they are needed. Python lists, in contrast, we describe as “strict”.
itertools.count produces a sequence of numbers incrementing by some fixed interval. This iterator is always infinite, so we will use
islice to take portions of it when we give examples.
The first parameter of
count specifies where to start. For example,
count(2) enumerates the integers increasing from 2.
The Haskell equivalent is
Prelude for example,
enumFrom 2 enumerates the integers increasing from 2.
This is commonly written using range syntax;
[2..] has the same meaning.
The optional second parameter to
count specifies how much each subsequent value will change from the previous value. By default, it increments by 1. Here we show incrementing by two:
The simplest way to accomplish this in Haskell is with a more general function called
The first parameter to iterate specifies how each subsequent value will change from the previous value. For example, to increment by two:
You can use a negative
step to count downward:
Just as you can use
(\x -> x - 1) (“subtract one”) as the function argument to
cycle a list
itertools.cycle is to replay it over and over in a never-ending loop.
Here we print the first six elements of the infinite iterator:
The Haskell function
Prelude is the same.
itertools.repeat is similar to
cycle, but its parameter is a single value, not an iterable.
It produces a never-ending repetition of its argument.
Again we demonstrating by printing only the first handful of outputs:
Again the Haskell function
Prelude is the same as the Python function.
times parameter allows us to specify some fixed number of repetitions to get a finite result.
Because Haskell does not overload function names with differing arities as Python does, the Haskell equivalent
Prelude is a separate function with a different name: