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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With