Reputation: 137
I am trying to recursively find the nth element in a list in ocaml using the following code.
let rec get_val x n = match x with
[] -> -1
| h::t -> if (n=0) then h else get_val t (n-1)
;;
print_int get_val [1; 2; 3] 1;;
However this code is giving me the error
This function has type int -> unit
It is applied to too many arguments; maybe you forgot a `;'.
Upvotes: 0
Views: 176
Reputation: 66813
Your definition is asking for two separate parameters (i.e., it is curried). But you're passing a pair of parameters (t, n - 1)
. These aren't the same thing.
To get past this problem, change the recursive call to get_val t (n - 1)
.
You might consider raising the Not_found exception when the list is too short. That way your code will work for lists of all types.
Update
Now the error is in the line where you test your function. You need parentheses there as well.
(You shouldn't keep changing your code. People who come to this page later won't be able to follow the questions and answers.)
Upvotes: 0