tags:

views:

233

answers:

3

The pairs function needs to do something like this:

pairs [1, 2, 3, 4] -> [(1, 2), (2, 3), (3, 4)]
+19  A: 
pairs [] = []
pairs xs = zip xs (tail xs)
Dietrich Epp
You should be ok with just the second line since `zip [] undefined` is `[]`
rampion
Oh, you're right. I didn't think of that.
Dietrich Epp
+4  A: 

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
Chuck
`pairs (x:y:rest) = (x,y) : pairs (y:rest)` would also work, avoiding the need for `@`, although at the cost of an extra constructor.
ephemient
+8  A: 

You could go as far as

import Control.Applicative (<*>)
pairs = zip <*> tail

but

pairs xs = zip xs (tail xs)

is probably clearer.

Edward Kmett