Interleave two lists

Adrian Hey ahey at
Sun Aug 24 17:17:41 EDT 2008

Sean Leather wrote:
> Mark Jones gave several talks at Advanced Functional Programming 2008. In
> one of them, he presented approaches to enumerating the elements of various
> datatypes. I found several interesting things in it, but one function stuck
> out as being perhaps useful in general.
> infixr 5 |||
> (|||) :: [a] -> [a] -> [a]
> []     ||| ys = ys
> (x:xs) ||| ys = x : ys ||| xs
> It interleaves the elements of two lists. It's defined exactly as (++) with
> the exception that the arguments are swapped for the recursive application.
> This works nicely when one wants to merge infinite lists. For example,
> suppose you want a list of the enumerable numbers with a balance of positive
> and negative:
> enums :: (Num a, Enum a) => [a]
> enums = [0..] ||| map negate [1..]
> You can't use (++) here, because the left side never completes.
> Does (|||) seem useful to others? Is it already available in some other form
> (or in a library) of which I'm not aware? If yes and no are the answers,
> then I wonder if it's useful enough for Data.List (modulo any expected
> renaming).

It seems like it would be difficult to extend this definition (to
interleave 3 or more lists) in a fair manner. You could probably do
better using a revolving (Data.)sequence of lists.

Just an idea..

Adrian Hey

More information about the Libraries mailing list