Proposal: Add functions to get consecutive elements to Data.List

Roman Cheplyaka roma at ro-che.info
Wed Apr 13 07:38:02 UTC 2016


-1

zip xs (tail xs) is a simple, well-known idiom. If you think there's an
education problem, you could document and explain it in the haddock for
zip or zipWith.

As you note yourself, there is no problem with empty lists. If you are
worried about tail, use drop 1 as David suggests.

On 04/12/2016 11:55 PM, Johan Holmquist 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.
> 
> 
> Deadline for discussion: 2016-05-31.
> 
> 
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/libraries
> 



More information about the Libraries mailing list