I am trying to write a simple merge sort code in OCaml, which also removed duplicates.
The code that I have written is:
let mergesort l r =
match l with
[] -> []
| [x]-> [x]
| x::xs -> let rec split l3 =
match l3 with
[] -> ([], [])
| [h] -> ([h], [])
| h1::h2::t -> let (left, right) = split t in
(h1::left, h2::right) in
let rec merge l1 l2 r =
match (l1, l2) with
([], []) -> []
| ([a], []) -> [a]
| ([], [a]) -> [a]
| (a1::t1, a2::t2) -> if a1 = a2 then (a1::(merge (t1) t2))
else if r(a1, a2) then (a2::(merge t1 (a2::t2)))
else (a1::(merge (a1::t1) t2)) in
let (l3, l4) = split l in
merge (mergesort l3 r) (mergesort l3 r) r;;
I am getting following type error in my merge function:
|(a1::t1, a2::t2) -> if a1 = a2 then
(a1::(merge (t1) t2))
Error: This expression has type 'a -> 'b list but an expression was expected of type 'b list
I have no idea why I am getting this error, as all the branches in merge are returning the list of same type.
Can anyone help here?
merge
takes 3 arguments; you're calling it with 2. – melpomene(a2::(merge t1 (a1::t2)))
and(a1::(merge (a2::t1) t2))
. You can also write this better using| (a1::t1 as left, a2::t2 as right) -> ...
and using left/reight later. This saves the compiler form allocating a new list for the recursive call. – Goswin von Brederlow