Home > Back-end >  Merge two lists in haskell
Merge two lists in haskell

Time:12-13

I get this function to merge two lists in haskell:

merge :: [a] -> [a] -> [a]
merge xs     []     = xs
merge []     ys     = ys
merge (x:xs) (y:ys) = x : y : merge xs ys

but i want this function merge :: ([a],[a]) -> [a], how do I make this change?

CodePudding user response:

There is an uncurry function, which can be helpful in such situations. Quote:

uncurry converts a curried function to a function on pairs.

In this case, we can use it to derive merge' from merge:

merge' :: ([a], [a]) -> [a]
merge' = uncurry merge

merge' ([1],[2]) == [1, 2] --> True

CodePudding user response:

You could reuse the merge function to make it work for tuples of lists as follows:

merge :: [a] -> [a] -> [a]
merge xs     []     = xs
merge []     ys     = ys
merge (x:xs) (y:ys) = x : y : merge xs ys

mergeTuples :: ([a], [a]) -> [a]
mergeTuples (xs, ys) = merge xs ys

CodePudding user response:

You change

merge1 :: [a] -> [a] -> [a]
merge1    xs     []   = xs
merge1    []     ys   = ys
merge1  (x:xs) (y:ys) = x : y : merge1 xs ys

to

merge2 :: ([a], [a]) -> [a]
merge2    ( xs, [] )  = xs
merge2    ( [], ys )  = ys
merge2   (x:xs, y:ys) = x : y : merge2 (xs, ys)

merge1 is known as a "curried" functions, and merge2 as "uncurued".

The functions curry and uncurry go between the two forms by packaging/unpackaging the arguments as needed, and calling the given function:

curry   f  x y  = f (x,y)
uncurry g (x,y) = g  x y

Thus merge1 = curry merge2 and merge2 = uncurry merge1, but you have to actually define at least one of them to implement the actual functionality.

  • Related