问题描述
我正在尝试在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) ;;
$ 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
当我用任意的正值(上面的493)替换-1
时,一切正常。
这是怎么回事?
解决方法
OCaml在这种情况下将-
解释为二进制运算符。您必须括号(-1)
。
这是常见的OCaml陷阱。