为什么 OCaml 编译器会给出有关类型推断的错误消息?

Why does OCaml compiler give this error message regarding type inference?

我已经在 OCaml 中编写了这个辅助函数,但它一直抛出这个错误。

代码:

let rec helper1 f lines d =
        match lines with
        | [] -> None
        | h::t when ( helper2 f h 0) <> -1 -> Some (d, (helper2 f h 0))
        | _::t -> helper1 f t d+1;;

错误:

|_::t -> helper1 f t d+1;;
          ^^^^^^^^^^^^^
Error: This expression has type ('a * int) option
       but an expression was expected of type int

我需要 ('a *int) option 这样的类型,据我看来它看起来还不错。我是 OCaml 的新手,如有任何帮助,我们将不胜感激!

这是学习OCaml时经常遇到的问题。你假设,

f x+1

翻译为

f (x+1)

而实际上它的意思是,

(f x) + 1

更正式地说,在 OCaml 中,函数应用运算符,表示为函数名称及其参数的并列,比中缀运算符(例如,+-*、等等)。

现在错误消息有了明确的解释,因为您已经

helper1 f t d + 1

编译器看到您向 1 添加了某些内容 (helper1 f t d),并推断该内容的类型应为 int。另一方面,根据 helper1 的其他出现,它也推断出它具有类型 ('a * int) option,这显然不是 int。所以提示错误。