Reputation: 83
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
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