Search code examples
f#unary-operator

Why does F# have a unary plus operator?


Some languages use a unary plus operator for implicit conversions, such as coercing a string to a number (e.g. Javascript) or casting small number types to an int (e.g. most C-based languages), or to be used when overloading operators.

Since the unary plus is primarily used for hackish purposes like this, and also since F# does not perform automatic widening conversions, I was surprised that F# includes the unary plus.

What adds to my surprise is that Haskell does not have a unary plus operator. Since the F# design was influenced by Haskell, I'm curious as to why it was decided that F# needed a unary plus when Haskell apparently didn't.

Can you give an example of a credible use for the unary plus in F#? If you can't, why is it included in the language at all?


Solution

  • I'll summarize the extended comments. Possible reasons (until a more authoritative answer is given):

    1. Consistency with OCaml, from which F# is derived (if you're doing something wrong/unnecessary it's best to keep doing it so people know what to expect :-))
    2. Overloading (mostly for custom types)
    3. Symmetry with unary negation