-2

I need to write a function to merge two lists. Exactly like '++' is working.

let x = merge [1,2,3] [3,3,4] -- should output [1,2,3,3,3,4]

How should it be done?

Edit: solution is

merge :: [a] -> [a] -> [a]
merge []     ys = ys
merge (x:xs) ys = x : (merge xs ys)
user3235761
  • 1
  • 2
  • 5

1 Answers1

1

Maybe something like this.

merge :: (a -> a -> Bool) -> [a] -> [a] -> [a]
merge pred xs []         = xs
merge pred [] ys         = ys
merge pred (x:xs) (y:ys) =
  case pred x y of
    True  -> x: merge pred xs (y:ys)
    False -> y: merge pred (x:xs) ys

(++) xs ys = merge (\x y -> compare x y == LT) xs ys

Or, if you just need to repeat the functionality of (++), you can look up it's definition with hoogle which eventually leads you to the source code

(++) []     ys = ys
(++) (x:xs) ys = x : xs ++ ys
Gebb
  • 6,371
  • 3
  • 44
  • 56