Proposal: Add functions to get consecutive elements to Data.List
Johan Holmquist
holmisen at gmail.com
Tue Apr 12 20:55:42 UTC 2016
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.
Deadline for discussion: 2016-05-31.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/libraries/attachments/20160412/d0d4fe36/attachment.html>
More information about the Libraries
mailing list