Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging 3 lists in Haskell

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 ?

like image 683
Meem Avatar asked Jan 24 '23 15:01

Meem


1 Answers

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.

like image 73
Fabián Heredia Montiel Avatar answered Feb 01 '23 14:02

Fabián Heredia Montiel