将负整数传递给 OCaml 中的函数时出错
Error when passing negative integer to a function in OCaml
如果我在 OCaml 中定义一个函数,例如 let f x = x + 1;;
然后我尝试调用它传递一个负数
f -1;;
它给我以下错误
Error: This expression has type int -> int
but an expression was expected of type int
为什么会出现这个错误?
基本上,它来自解析器的优先级。编译器认为 f -1
意味着你想用 1
减去 f
。已经被吐槽很久了
输入 f (-1)
或 f ~-1
将解决您的问题(稍后使用 "explicitly unary minus")。
更新:
如 OCaml manual 中所述:
Unary negation. You can also write - e instead of ~- e.
基本上,-
可以用作二元运算符 4 - 1
和一元运算符 -1
。但是,就像您的情况一样,可能会造成混淆:f - 1
是 "f minus one" 而不是 "f applied to minus one"。因此添加了 ~-
运算符以使其也具有非混淆的一元减号。
请注意,space 在这里并不重要,并且不会改变,因为许多已经存在的代码可能包含没有 space 的操作。
如果我在 OCaml 中定义一个函数,例如 let f x = x + 1;;
然后我尝试调用它传递一个负数
f -1;;
它给我以下错误
Error: This expression has type int -> int
but an expression was expected of type int
为什么会出现这个错误?
基本上,它来自解析器的优先级。编译器认为 f -1
意味着你想用 1
减去 f
。已经被吐槽很久了
输入 f (-1)
或 f ~-1
将解决您的问题(稍后使用 "explicitly unary minus")。
更新:
如 OCaml manual 中所述:
Unary negation. You can also write - e instead of ~- e.
基本上,-
可以用作二元运算符 4 - 1
和一元运算符 -1
。但是,就像您的情况一样,可能会造成混淆:f - 1
是 "f minus one" 而不是 "f applied to minus one"。因此添加了 ~-
运算符以使其也具有非混淆的一元减号。
请注意,space 在这里并不重要,并且不会改变,因为许多已经存在的代码可能包含没有 space 的操作。