user15263733
user15263733

Reputation: 83

Haskell pairing elements of a single list

Is there a way to pair elements up in a single list like this:

change [cat,dog,bird,rabbit] to [(cat,dog),(bird,rabbit)]

I know of the zip function but it combines two lists, how can I do this for one list?

Upvotes: 1

Views: 72

Answers (1)

delta
delta

Reputation: 3818

A possible approach to use zip is to zip the even-positioned elements of our list with the odd-positioned elements list:

takeEveryN :: Int -> [a] -> [a]
takeEveryN _ [] = []
takeEveryN n (x:xs) = x : takeEveryN n (drop (n - 1) xs)

zipList :: [a] -> [(a, a)]
zipList xs = zip (takeEveryN 2 xs) (takeEveryN 2 (drop 1 xs))

Upvotes: 1

Related Questions