dotnet / dotnet/fsharp

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

Open
#16,464 2 comments 3 reactions 0 assignees View on GitHub
Area-Compiler-Checking Area-Compiler-SRTP Bug Impact-Low
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 22h
Merged PRs (30d)
144

Description

**Steps required to reproduce the problem**

```fsharp
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:

```fsharp
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:

```fsharp
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.