To concatenate two Python iterators, we use
The resulting iterator consists of each element from the first argument (1 and 2), followed by each element of the second argument (3 and 4).
The corresponding Haskell function
Prelude. is called
(++) may be replaced with the more general operator
(<>), because conatenation is the semigroup operation for the list type.
Variadic vs infix
chain function is variadic; it can accept any number of arguments, not just two. This makes it easy to chain together any number of iterators without having to use nested function applications. The following two expressions are equivalent:
Haskell doesn’t have variadic functions, but it does let you define infix operators, Infix operators are not language built-ins, and you can define your own. which can be used to get a similar convenient effect. The
(++) function concatenates two lists, but infix notation makes it easy to chain together as many concatenations as you like.
We do not have to use parentheses to group the function applications, but if we did, it would look like this:
If any of the sequences in the chain is infinite, then it follows that the resulting sequence is also infinite. Here we extend the first example to add an infinite number of fives at the end, using the
repeat function we showed previously:
Regardless of whether the iterators ever stop, the code looks the same.
It only really makes sense to use an infinite list as the last part of a chain. There’s nothing stopping you from concatenating lists after the end of an infinite list, but it is pointless, since they will never be reached.
If you aren’t chaining together some fixed number of lists, but rather a list of lists, you can use