OCaml 错误表达式应为 int 类型(混淆错误)

OCaml error an expression was expected of type int (confusing error)

我的代码:

let safe_log10 = function x -> if (x <= 0.) then None else Some (log10 x);;

输入 -1.0,得到:

safe_log10 -1.0;;
Error: This expression has type float -> float option
       but an expression was expected of type int

但是,它与 (-1.0) 一起工作正常:

# safe_log10 (-1.0);;
- : float option = None

为什么会发生这种情况,我怎样才能修复该功能以供 safe_log10 -1.0 使用?谢谢。

-1.0写在一起没关系,这个-仍然是二元运算符,你的表达式看起来像function - float,这没有意义。在 OCaml 中,与许多其他语言不同,二进制 - 只能应用于 intint;即使对于浮点数,您也需要不同的运算符 -..