Reputation: 75
I am wondering how to merge 3 lists into one list.
here is merging two lists
merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) | x <= y = x:merge xs (y:ys)
| otherwise = y:merge (x:xs) ys
what should I do if I want to merge three lists ?
Upvotes: 4
Views: 501
Reputation: 1687
Your merge
function can already merge two lists and since it is a binary associative operation you could do:
list1 `merge` (list2 `merge` list3)
Or more generally if you want to merge an arbitrary number of lists:
mergeAll :: Ord a => [[a]] -> [a]
mergeAll = foldl merge []
Wikipedia has a great explanation on Folding.
Upvotes: 8