Code:
let rec get_val (x, n) = match x with
[] -> -1
| if (n=0) then (h::_) -> h
else (_::t) -> get_val(t, n-1)
;;
Error message:
Characters 55-57: | if (n=0) then (h::_) -> h ^^ Error: Syntax error
Code:
let rec get_val (x, n) = match x with
[] -> -1
| if (n=0) then (h::_) -> h
else (_::t) -> get_val(t, n-1)
;;
Error message:
Characters 55-57: | if (n=0) then (h::_) -> h ^^ Error: Syntax error
I think the problem is that you are trying to put an if
expression into a pattern-matching statement. The left-hand side of each ->
needs to correspond to a valid pattern for x
.
Try this:
let rec get_val (x, n) = match x with
[] -> -1
| h::t -> if (n=0) then h
else get_val(t, n-1)
;;
You can't mix if and match like that, you must either use the if after the pattern, as already proposed, or use guarded patter as in:
let rec get_val x n =
match x with
[] -> -1
| h::_ when n=0 -> h
| _::t -> get_val t (n-1)
;;
note also that ocaml is curried, and you don't usually put parenthesis around function's arguments