David Turner dct25-561bs at mythic-beasts.com
Wed Apr 13 06:47:42 UTC 2016

```Hi there,

The idiom I normally use for this is 'zip xs (drop 1 xs)'. By using 'drop
1' instead of 'tail' it handles the empty case without partiality or
needing an extra equation. Does that work for you?

Cheers,

David
On 12 Apr 2016 21:55, "Johan Holmquist" <holmisen at gmail.com> wrote:

I propose adding two new functions to Data.List:

zipConsecutives :: [a] -> [(a,a)]
zipConsecutives xs = zip xs (tail xs)

zipConsecutivesWith :: (a -> a -> b) -> [a] -> [b]
zipConsecutivesWith f xs = zipWith f xs (tail xs)

(with possibly more efficient implementations)

The Trac feature request is at https://ghc.haskell.org/trac/ghc/ticket/11815
.

Why

These functions are useful when one wants to process consecutive pairs
of elements in a sequence, which is not uncommon. The ticket lists
some examples, reiterated here:

-- diff consecutive elements:
diffs = zipConsecutivesWith (flip (-))

-- determine if list is ascending (similar for descending and strict):
isAscending = and . zipConsecutivesWith (<=)

-- an old friend of ours:
fibs = 1 : 1 : zipConsecutivesWith (+) fibs

-- get the edges of a closed path defined by points (ps):
edges ps = zipConsecutivesWith makeEdge (ps ++ take 1 ps)

Why add to Data.List (and base)

The definition must either use an extra equation for the empty list case:

zipConsecutives [] = []
zipConsecutives xs = zip xs (tail xs)

which makes it non practical to define inline at each use site. Or one
may omit the empty list equation, which is safe (thanks to laziness),
but that may not be immediately obvious. (It wasn't to me anyway.) The
tail function is generally considered unsafe so it is not desirable to
force the user to use it. The proposed functions would offer an
alternative.

The Data.List module is often imported unqualified, so new identifiers
may cause collissions. I do find it rather unlikely that the proposed
names would cause such problems, however.