fslang-suggestions icon indicating copy to clipboard operation
fslang-suggestions copied to clipboard

Allow any type constraints on SRTP

Open WhiteBlackGoose opened this issue 4 years ago • 2 comments

Constrain any type instead of type parameter

I suggest adding the following feature to the language: being able to constrain any type in SRTP, not only the generic type parameter.

Let me show an example:

let inline addTwoThings< ^a, ^b, ^c when Tuple< ^a, ^b> : (member add : () -> ^c)> (a : ^a) (b : ^b) =
    (a, b).add()

So instead of constraining ^a, ^b I constrained Tuple< ^a, ^b> of these two arguments to have method add.

Same goes with any type computed of type arguments, it could be

when Tuple<^a list, ^b option> : (static member something : () -> ^a * ^b)

It integrates smooth with HKTs:

^a, ^b, ^h when ^h< ^a> : (static member bind : ^a -> ^h< ^b>)

Pros and Cons

Pros: useful for cases when we partially extend a generic type (that is, not covering its all type parameters), I mean the following example:

type Tuple<string, int> with
    member add () -> $"{Item1} {Item2}"

It also makes the C# interop more convenient. Here's sum via Linq:

let inline sum< ^a when seq< ^a> : (member Sum : unit -> ^a)> s = s.Sum()

Cons: complicates the syntax for SRTP.

Extra information

Estimated cost (XS, S, M, L, XL, XXL):

Related suggestions: HKT

Affidavit (please submit!)

Please tick this by placing a cross in the box:

  • [x] This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • [x] I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • [x] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • [x] This is not a breaking change to the F# language design
  • [ ] I or my company would be willing to help implement and/or test this

For Readers

If you would like to see this issue implemented, please click the :+1: emoji on this issue. These counts are used to generally order the suggestions by engagement.

WhiteBlackGoose avatar Feb 09 '22 19:02 WhiteBlackGoose

It's an interesting proposal....

dsyme avatar Apr 13 '23 14:04 dsyme

Wouldn't add in the example need to be an extension method? So wouldn't this just be https://github.com/fsharp/fslang-design/blob/main/RFCs/FS-1043-extension-members-for-operators-and-srtp-constraints.md

kevmal avatar Apr 13 '23 14:04 kevmal