How do you write the function 'pairs' in Haskell?

前端 未结 4 611
萌比男神i
萌比男神i 2021-02-07 04:50

The pairs function needs to do something like this:

pairs [1, 2, 3, 4] -> [(1, 2), (2, 3), (3, 4)]
4条回答
  •  花落未央
    2021-02-07 05:32

    Just for completeness, a more "low-level" version using explicit recursion:

    pairs (x:xs@(y:_)) = (x, y) : pairs xs
    pairs _          = []
    

    The construct x:xs@(y:_) means "a list with a head x, and a tail xs that has at least one element y". This is because y doubles as both the second element of the current pair and the first element of the next. Otherwise we'd have to make a special case for lists of length 1.

    pairs [_] = []
    pairs []  = []
    pairs (x:xs) = (x, head xs) : pairs xs
    

提交回复
热议问题