如何在F#中显式调用Microsoft.ML.Probabilistic的&运算符?
Variable<bool> & Operator The issue here is that F# handles operator resolution differently than C#. In C#, the compiler will prioritize custom overloaded operators when they match operand types, but F# treats & as a native boolean logical operator that strictly expects bool operands by default. That’s why you’re getting the error saying your Variable<bool> values should be bool instead.
Here are a few straightforward ways to fix this:
1. Use the explicit Variable.And static method
Microsoft.ML.Probabilistic provides a direct static method equivalent to the & operator, which works perfectly in F#:
let main argv = let firstCoinHeads = Variable.Bernoulli 0.5 let secondCoinHeads = Variable.Bernoulli 0.5 let bothHeads = Variable.And(firstCoinHeads, secondCoinHeads)
2. Call the operator's underlying static method
Every overloaded operator in .NET has a corresponding static method name, and for & that’s op_BitwiseAnd. You can call this method directly to invoke the correct operator logic:
let main argv = let firstCoinHeads = Variable.Bernoulli 0.5 let secondCoinHeads = Variable.Bernoulli 0.5 let bothHeads = Variable.op_BitwiseAnd(firstCoinHeads, secondCoinHeads)
3. Create a custom infix operator (for cleaner syntax)
If you want syntax closer to the C# version, you can define your own F# infix operator that wraps the Variable.And method. This lets you use a symbol that behaves the way you expect:
// Define a custom infix operator for Variable<bool> logical AND let inline ( &&& ) left right = Variable.And(left, right) let main argv = let firstCoinHeads = Variable.Bernoulli 0.5 let secondCoinHeads = Variable.Bernoulli 0.5 let bothHeads = firstCoinHeads &&& secondCoinHeads
All three approaches will achieve the exact same logic as your original C# code, resolving the compilation error.
内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd

