These are chat archives for Microsoft/visualfsharp

14th
Nov 2017
robertj
@robkuz
Nov 14 2017 09:29

Is there a reason why it is not possible to implement generic methods on a interface implementation?

type IMap =
     abstract member Map: 'a -> 'b

type MapIntString() =
    interface IMap with
    member this.Map(x:int): string = sprintf "%i" x

type MapStringToInt() =
    interface IMap with 
    member this.Map(x:string): int = 0

I know I can

type IMap<'a, 'b> =
     abstract member Map: 'a -> 'b

type MapIntString() =
    interface IMap<int, string> with
    member this.Map x = sprintf "%i" x

type MapStringToInt() =
    interface Map<string, int> with
    member this.Map (x:string): int = 0

But that is not always possible or leads enormous amounts of code.
for example

type MapFoo(f: 'a -> 'b) =
    interface Map with
    member this.Map (x:Foo<'a>): Foo<'b> = 
       let (Foo a) = x
       Foo (f a)
robertj
@robkuz
Nov 14 2017 09:45

In the above example at the moment I would have to create a specialized impl for any combination of 'a and 'b of Foo<_> whereas with an implementation like MapFoo I just need the functions that do the conversion and give one of these functions during construction time
So my question is: are there any hard technical limitations (CLR/.NET) or type theory or type inferrence that prevents this? And if so why is it even possible to define the interface like

type IMap =
     abstract member Map: 'a -> 'b

Why not have a compiler error when trying to define a generic abstract method that uses generic types that are not defined on the type itself?