Reputation: 7172
I am trying to find the last occurrence of some integer in an array in ocaml:
let rec findLastHelper l i loc ret =
match l with
| [] -> ret
| x::xs ->
match x == i with
| true -> findLastHelper xs i (loc+1) loc
| _ -> findLastHelper xs i (loc+1) ret ;;
let findLast l i = (findLastHelper l i 0 -1) ;;
(* let findLast l i = (findLastHelper l i 0 493) ;; *)
let main = Printf.printf "%d\n" (findLast [ 1 ; 6 ; 8 ; 2 ; 9 ; 8 ] 7) ;;
If the integer doesn't exist, the code should return -1
. When I compiled it, I got the following error:
$ ocamlopt main.ml -o main
File "main.ml", line 9, characters 20-40:
Error: This expression has type int -> int
but an expression was expected of type int
When I replace the -1
with some arbitrary positive value (493 above), everything goes fine.
What is going on here?
Upvotes: 3
Views: 400
Reputation: 423
OCaml is interpreting -
as a binary operator in this context. You have to parenthesize (-1)
.
This is a common OCaml gotcha.
Upvotes: 3