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 ?
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.