0

I started learning OCaml and I have a problem with a simple function. This is from Developing Application with Objective OCaml

Write a general function merge which takes as argument a comparison function and two lists sorted in this order and returns the list merged in the same order. The comparison function will be of type 'a -> 'a -> bool.

Here is what I got so far

(* func : 'a -> 'a -> bool) *)
let rec merge2 listA listB func = match listA, listB with
    | list, [] | [], list -> list
    | (headA :: tailA), (headB :: tailB) -> 
        if (func headA headB) then headA :: merge2 tailA listB
        else merge2 :: merge listA tailB

and here is a error message

Characters 169-187:
        if (func headA headB) then headA :: merge2 tailA listB
                                        ^^^^^^^^^^^^^^^^^^
Error: This expression has type ('a -> 'a -> bool) -> 'a list
       but an expression was expected of type 'a list

I don't understand wht I get this error message. Obviously a dummy function

let foo a b f = if (f a b ) then true else false

work just fine. I also tried to state types explicitly.

EDIT:

Correct code

let rec merge2 listA listB func = match listA, listB with
    | list, [] | [], list -> list
    | (headA :: tailA), (headB :: tailB) -> 
        if (func headA headB) then headA :: merge2 tailA listB func
        else headB :: merge2 listA tailB func
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108

1 Answers1

2

Obviously, merge2 takes 3 arguments but you supplied only 2 arguments in the recursive calls. There are several typos in the else branch as well (merge2 should be headB while merge should become merge2).

To avoid such mistakes, it is a good idea to move least-frequently-changed arguments upfront:

let rec merge2 f xs ys = 
    match xs, ys with
    | zs, [] | [], zs -> zs
    | x::xs', y::ys' -> 
        if f x y then x::merge2 f xs' ys
        else y::merge2 f xs ys'
pad
  • 41,040
  • 7
  • 92
  • 166