Home > Blockchain >  How do I properly use INumber in .NET 7 in F#?
How do I properly use INumber in .NET 7 in F#?

Time:11-11

I was reading the following on .NET 7 and INumber:

It gave an example of adding two INumber generic values, which I tried to replicate in F# to no success.

let add<'T when 'T :> INumber<'T>>
    (left : 'T) (right: 'T) : 'T =
    left   right

This gives "The declared type parameter 'T cannot be resolved at run time. When I try a different way, to be super clear:

let add<'T when 'T :> INumber<'T>>
        (left : 'T) (right: 'T) : 'T =
        INumber<'T>.`` `` left right

"INumber<'T'>. is not defined."

Please can someone help me understand how to make this work, and provide the correct format for something like this?

CodePudding user response:

As written in the .NET 7 release notes for .NET 7 support in Visual Studio you need to install 17.4 version:

You need Visual Studio 17.4 latest preview to use .NET 7.0 on Windows. On macOS, you need the latest version of Visual Studio for Mac. The C# extension for Visual Studio Code supports .NET 7.0 and C# 11.

CodePudding user response:

As Guru Stron mentioned, the first snippet should work fine. If you want to explicitly access a member of the interface instead (your second snippet), I think it would be:

let add<'T when 'T :> INumber<'T>>
    (left : 'T) (right: 'T) : 'T =
    'T.op_CheckedAddition(left, right)

This syntax is new in F# 7.0.

CodePudding user response:

Thank you to @GuruStron for suggesting to update VS 2022. I am now on v 17.4 and the first snippet resolves.

Thank you!

  • Related