Skip to content

Can't use addition (substruction) multiple times in member for constrained to INumber<> generic  #16464

Description

@gurustron

Steps required to reproduce the problem

type Test<'T when 'T:> INumber<'T>> = 
  { One: 'T;
    Two: 'T; 
    Three: 'T } with
  member this.ThreeSum = this.One + this.Two + this.Three 

Expected behavior

Compiles

Actual behavior

error FS0670: This code is not sufficiently generic. The type variable ^T when ^T :> INumber<^T> could not be generalized because it would escape its scope.

Known workarounds

Intermediate member or using type-defined methods:

type Test<'T when 'T:> INumber<'T>> = 
  { One: 'T;
    Two: 'T; 
    Three: 'T } with
  member this.TwoSum = this.One + this.Two
  member this.ThreeSum = this.TwoSum + this.Three
  member this.ThreeSum1 = 'T.op_CheckedAddition('T.op_CheckedAddition(this.One, this.Two), this.Three)

Related information

Provide any related information (optional):

  • Operating system: Windows 11
  • .NET Runtime kind (.NET Core, .NET Framework, Mono)
    .NET SDK:
    Version: 8.0.100
    Commit: 57efcf1350
    Workload version: 8.0.100-manifests.8d38d0cc
  • Editing Tools Rider/CLI

Extra notes

inline member with + constraint works:

type Test1<'T when 'T : (static member (+) : 'T -> 'T -> 'T)> = 
  { One: 'T;
    Two: 'T; 
    Three: 'T } with
  member inline this.TwoSum = this.One + this.Two + this.Three

But similar approach with INumber<> fails:

type Test<'T when 'T:> INumber<'T>> = 
  { One: 'T;
    Two: 'T; 
    Three: 'T } with
  member inline this.ThreeSum1 = this.One + this.Two - this.Three

error FS0339: The signature and implementation are not compatible because the type parameter in the class/signature has a different compile-time requirement to the one in the member/implementation

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Compiler-CheckingType checking, attributes and all aspects of logic checkingArea-Compiler-SRTPbugs in SRTP inference, resolution, witness passing, code genBugImpact-Low(Internal MS Team use only) Describes an issue with limited impact on existing code.

    Type

    Projects

    Status
    New

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions