Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 317
Peter Olson Avatar asked Nov 03 '11 16:11

Peter Olson


2 Answers

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
like image 107
Daniel Avatar answered Sep 26 '22 01:09

Daniel


F# has two core influences:

  1. OCaml, with which it was originally compatible, and
  2. the CLR, on which it is built.

As has been pointed out, OCaml has a unary plus operator, so from that point of view, it was natural for F# to have one as well.

As for the CLR... To my surprise, the Common Language Specification doesn't specify any requirements for languages to support operator overloading. However, it does specify semantics and naming conventions when the mechanism is used. Still, F# was allowed to opt out of using unary plus, just like C# and VB opted out of support for overloading compound assignment operators (+=, etc.).

The most common .NET languages aside from F# (C#, VB and C++/CLI) do allow it and have a unary plus. So from this point of view as well it would be natural for F# to have support for a unary plus operator.

like image 42
Jeffrey Sax Avatar answered Sep 22 '22 01:09

Jeffrey Sax