0
votes

I just began to learn Ocaml recently and now just started to practice some codes. In this case, I tried to find a maximum number in a list but it keeps return me an error message.

let max: int list -> int
= fun lst ->
match lst with
 |[] -> 0
 |h::[] -> h
 |h::t -> let a = max t in
            if h < a then h
            else
             a;;

Ocaml keeps saying:

Error: This expression has type int list -> int list but an expression was expected of type int.

I don't understand why a is an int list though I claimed it as a max t which is a function that makes int list into int... Thanks for yout help.

1

1 Answers

2
votes

a has type int list -> int list because max in let a = max t does not refer to your function, but to the one defined in Stdlib. Stdlib (Previously called Pervasives) contains definitions used very commonly and is therefore opened for you by default.

Stdlib.max has the type 'a -> 'a -> 'a. So when you pass it an int list, the compiler infers 'a to be int list and returns a function with type int list -> int list.

Why does max not refer to your own max function? Because you've forgotten the rec keyword. As you probably know already, rec makes the function available to be called inside itself.

You should avoid shadowing Stdlib function names to avoid confusing errors like this. If you had chosen a different name, you'd simply get an error telling you that max does not exist.