fsharp / fslang-suggestions

The place to make suggestions, discuss and vote on F# language and core library features
345 stars 21 forks source link

SRTP should support multiple overloads of a method #1342

Open nodakai opened 9 months ago

nodakai commented 9 months ago

I propose we enable compilation of the following SRTP function:

let inline f(t: ^T when ^T: (member Foo: int -> int) and ^T: (member Foo: float -> float)) =                                                                                                                                     
  printfn "%d" <| (^T: (member Foo: int -> int) (t, 0))                                                                                                                                                                          
  printfn "%f" <| (^T: (member Foo: float -> float) (t, 0.)) 

(This could also be adapted to the simplified syntax introduced in F# 7)

The existing way of approaching this problem in F# is to handle reference types or immutable structs by passing them as two separate arguments, each with its own SRTP type parameter. However, this approach is not feasible for mutable structs or structs following the builder pattern.

Pros and Cons

The advantages of making this adjustment to F# are primarily enhancing the language's consistency and expanding its capabilities.

The disadvantages of making this adjustment to F# are potentially introducing more complexity into the compiler's implementation.

Extra information

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

Related suggestions: (put links to related suggestions here)

Affidavit (please submit!)

Please tick these items by placing a cross in the box:

Please tick all that apply:

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.

voronoipotato commented 3 months ago

yeah I think one of the ways people have hacked around this is by adding dummy arguments to the end. It's very stupid, but it does seem to work.

type ICounts() =
     static member inline Count< ^C when ^C: (member itemCount: int)> o =  (^C: (member itemCount: int) o)
     static member inline Count< ^C, 'Dummy1 when ^C: (member thingCount: int)> o =  (^C: (member thingCount: int) o)
     static member inline Count< ^C, 'Dummy1, 'Dummy2 when ^C: (member otherCount: int)> o =  (^C: (member otherCount: int) o)
     static member inline Count< ^C, 'Dummy1, 'Dummy2, 'Dummy3 when ^C: (member Count: int)> o =  (^C: (member Count: int) o)

let say count = 
    printfn "%d" count
    ()

type c = ICounts

say (c.Count {|itemCount = 1|})
say (c.Count {|thingCount = 2|})
say (c.Count {|otherCount = 3|})
say (c.Count {|Count = 4|})