سؤال

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?

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

There is a unary plus operator in standard mathematical notation. Most programming languages have standard math notation as the original influence and motivation for the syntax of arithmetic expressions.

According to the this "Used to declare an overload for the unary plus operator."

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top