如何修改 OCaml 中的一元运算符?
在 OCaml 中,很容易访问二元运算符,例如“+”:
# (+);;
( + ) : int -> int -> int
并按照我的意愿修改它们:
# let (+) = (+.);;
( + ) : float -> float -> float
在 Pervasives 文档中,它说 (~-)
是一元运算符对应于(-)
,表示~-5
返回- :int = -5
。
修改 (~-)
也很容易:
let (~-) = (~-.);;
(~-) : float -> float
幸运的是,OCaml 允许用户使用 (-)
作为 (~-)
的别名code>:
假设我们已经定义了
foo : int -> int -> int
我们可以调用
foo 1 (-1);;
,这比好吧
foo 1 (~-1);;
,问题是,当我更改 (~-)
定义时,它不会影响一元运算符 (- )
...
let (~-) x = 5;;
~-2;;
- : int = 5
-2;;
- : int = -2
知道如何修改一元(-)
也是如此吗?
In OCaml, it is very easy to access to a binary operator, such as "+":
# (+);;
( + ) : int -> int -> int
And modify them as I wish:
# let (+) = (+.);;
( + ) : float -> float -> float
In the Pervasives documentation, it says that (~-)
is the unary operator corresponding to (-)
, meaning that ~-5
returns - :int = -5
.
It is easy to modify (~-)
as well:
let (~-) = (~-.);;
(~-) : float -> float
Fortunately, OCaml allows the user to use (-)
as an alias for (~-)
:
Suppose we have defined
foo : int -> int -> int
We can call
foo 1 (-1);;
which is way better than
foo 1 (~-1);;
Well, the problem is, when I change (~-)
definition, it doesn't affect the unary operator (-)
...
let (~-) x = 5;;
~-2;;
- : int = 5
-2;;
- : int = -2
Any idea how to modify the unary (-)
as well ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所说,一元
(-)
是(~-)
的快捷方式。实际上,您的更改影响了一元(-)
;例如,在重写(~-)
后,您可以通过多种方式使用(-)
:因此,当您将表达式传递给
(- )
。如果您调用-2
,它将被解析为一个值,而不是一个函数应用程序。遵循负数的正常约定是有意义的。顺便说一句,我不建议您使用这种覆盖运算符的方式。由于您已更改具有该运算符的任何数据类型的
(-)
,因此可能会导致混乱和奇怪的错误。As you said, unary
(-)
is a shortcut for(~-)
. Actually, your change has affected unary(-)
; for example, you have many ways to use(-)
as you want after overriding(~-)
:So it works when you pass an expression to
(-)
. In case you call-2
, it will be parsed as a value, not a function application. It makes sense to follow the normal convention of negative numbers.BTW, I don't recommend you to use this way of overriding operators. Since you have change
(-)
for any datatype having that operator, it may lead to confusion and strange bugs.这是编译器的代码摘录,似乎可以处理这种情况。请注意,它仅适用于浮点常量。这不是
-
运算符的一般功能。(您可以在 parser.mly 中找到此代码。)
我认为没有办法在不破坏编译器的情况下获得您想要的东西。
Here's a code extract from the compiler that seems to handle this case. Note that it only works for floating point constants. It's not a general feature of the
-
operator.(You'll find this code in parser.mly.)
I don't think there's a way to get what you want without hacking on the compiler at this spot.