What is the unary addition operator for?

I was browsing the Pervasives documentation just now when I encountered a strange “unary addition” operator, which seems at first to be the opposite of the unary negation operator (~-).

val (~+) : int -> int
    Unary addition. You can also write + e instead of ~+ e.
    Since 3.12.0

When I tested it out, the unary negation operator was pretty straightforward:

# 1;;
- : int = 1
# ~- 1;;
- : int = -1
# ~- (~- 1);;
- : int = 1

But the unary addition operator didn’t seem to make much sense except as an identity operator.

# ~+ 1;;
- : int = 1
# ~+ (~+ 1);;
- : int = 1
# ~+ (~- 1);;
- : int = -1

While the unary negation actually performs a negation, the unary addition operator just seems to do… nothing. Though, I suppose this could makes sense mathematically speaking… given that:

a + (-b) = a - b

However, to me, it does seem a bit out of place in Pervasives. Does anyone know of any actual uses for this operator?

1 Like

The unary plus operator was in de facto syntax of OCaml for quite a long time. Why it was added is a historical question, probably for the reasons of consistency or just accidentaly. Recently, the unary plus operator was made legal. See the following OCaml Mantis discussion, that explains why it was not removed, although everyone more or less agree that it is useless.


Here https://github.com/ocaml/ocaml/pull/222#issuecomment-126721989 @damiendoligez notes that

I’m on the fence where “unary +” is concerned: on the one hand it’s not used in any OCaml program currently existing (as far as I know), but on the other hand the principle of least astonishment says we should keep it (because most people would expect it to work).

So it will probably not be removed (unlike the other constructs).