Define operator F # '**' in C #

I see that F # uses the ** operator for permissions, so 2 ** 5 = 32 . This is different from C #, where you have the option of using the "^" operator in custom types, but for some reason is not used by built-in number types.

But how do you implement the ** operator in C # for use in an F # project?

If I do this in C #:

 public static Integer operator ^(Integer left, Integer right) { if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN; return left.RaiseToPower(right); } 

It compiles fine, and I can use it the same as the + operator, but none of them work in F #:

 let intgr3 = intgr1 ** intgr2 let intgr3 = intgr1 ^ intgr2 

And in C # this does not work:

 public static Integer operator **(Integer left, Integer right) { if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN; return left.RaiseToPower(right); } 

So, how to determine the equivalent of the F # operator ** in C #?
Thanks.

+6
source share
2 answers

As I said in my comments, C # does not allow you to define new operators, and ** not an operator in C #. ^ is an operator, but it is a logical XOR operator, not an exponential operator. This gave me a hint that F # might translate your C # statement into native F # ( ^^^ for logical XOR).

So, I created a couple of test projects and used your definition of ^ , here is what I found in F #:

 open CSLib // CSLib is the C# library let ( ** ) (x : Integer) (y : Integer) = x.RaiseToPower y let x = new Integer() let y = new Integer() let a = x ^ y // error let b = x ^^^ y // compiles, but looks like XOR let c = x ** y // compiles 

You can define new global operators in F #, however, if you want it to be a shared library, which might be unacceptable.

You can define the Exponentiation operator to use in F # by specifying the public static Pow method in type Integer in your C # library:

 public static Integer Pow(Integer left, Integer right) { if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN; return left.RaiseToPower(right); } 

Then you can use it directly in F # as ** . I note that overloaded operators in C # are not idiomatic, so the Pow method will seem quite natural to C # users.

+7
source

I believe that the reason you cannot define the ** operator for your object is because it is not one of the operators supported by the language. This is not a recognized operator. Why not just use the math library http://msdn.microsoft.com/en-us/library/system.math.pow.aspx

+2
source

Source: https://habr.com/ru/post/953957/


All Articles