I see that F# uses the **
operator for powers, so 2 ** 5 = 32
. This is different from C#, where you have the option to use the '^' operator in your custom types, but for some reason isn't used by the 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 way as the '+' operator, but neither of these work in F#:
let intgr3 = intgr1 ** intgr2
let intgr3 = intgr1 ^ intgr2
And in C#, this doesn't work:
public static Integer operator **(Integer left, Integer right)
{
if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN;
return left.RaiseToPower(right);
}
So how do I define the F# equivalent of the **
operator in C#?
Thanks.
On the internet, “F” is a slang term used to “pay respects” or commiserate in a tragic incident. Unlike other words we've covered, “F” isn't short for anything. It's almost entirely unrelated to the letter grade “F,” which means failure.
Summary of Key Points. "Drooling" is the most common definition for :F on Snapchat, WhatsApp, Facebook, Twitter, Instagram, and TikTok.
As I said in my comments, C# does not let you define new operators and **
is not an operator in C#. ^
is an operator, however it is the logical XOR operator, NOT the exponentiation operator. This gave me a hint that F# might be translating your C# operator into native F# (^^^
for logical XOR).
So, I created a couple test projects and using your definition of ^
, here's 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 this to be a general library that may not be acceptable.
You can define the Exponentiation operator for use in F# by defining a public static method Pow
in the Integer
type 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 are able to use it directly in F# as **
. I will note that overloaded operators in C# are not idiomatic so having a Pow
method will seem quite natural to C# users.
I believe the reason why you can't define a ** operator for your object is that this is not one of the operators supported by the language. It's not a recognized operator.. Why not just use the Math library http://msdn.microsoft.com/en-us/library/system.math.pow.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With