I have recently started working on OCAML. I am working from the book Modern Programming Languages, 2nd ed. The first chapter on ML has an exercise requiring the definition of a function max
of type int list -> int
to return the largest element from a list of integers. There is additionally a hint which suggests the inclusion of a helper function maxhelper
which as a second parameter takes the current largest element. Then max
is defined as :
fun max x = maxhelper (tl x, hd x)
I am trying to implement this in OCAML. Here is my code :
let max x =
let rec maxhelper x cur_max =
match x with
| [] -> cur_max
| h::t ->
if cur_max < h then maxhelper t h
else maxhelper t cur_max
in maxhelper List.tl(x) List.hd(x)
;;
This results in an error I cannot understand : This expression, i.e. List.tl(x)
on the last line has type 'a list -> 'a list
but an expression was expected of type ('b -> 'c -> 'd) list
What puzzles me is when I write the maxhelper function separately and give it arguments [2;3;4] 1
(original list being [1;2;3;4]
) it works correctly. Further, if I replace the arguments provided under in
as
in maxhelper x 0
The code compiles and works correctly (for non-negative numbers). I am not sure what I have missed regarding passing arguments to in
, or the error message I received. Mainly, why does the additional of a List()
call cause an error?
You're writing function calls as in an Algolic language, that's the basic problem I think.
Instead of
maxhelper List.tl(x) List.hd(x)
You should have
maxhelper (List.tl x) (List.hd x)
The way you wrote it, there are 4 parameters being passed to maxhelper
: List.tl
, x
, List.hd
, x
.