Implement F# interface via tacit programming

135 Views Asked by At

An idea from tacit programming is to not apply arguments to functions if it can be avoided.

Why doesn't F# allow this to compile if functions are first class members?

type IAdder =
    interface
    abstract member Add : int -> int -> int
end

type Adder =
    interface IAdder with
        member this.Add x y = x + y

type AdderWithInnerAdder(adder:IAdder) =
    interface IAdder with
        member this.Add = adder.Add

I get the compilation error...

No abstract property was found that corresponds to this override

I feel that this should compile. adder.Add clearly implements IAdder.Add and should be acceptable.

1

There are 1 best solutions below

5
Fyodor Soikin On BEST ANSWER

You can't assign interface members as if they were functions. Interfaces don't work like that. You have to specify the parameters:

    member this.Add x y = adder.Add x y

But interfaces are generally bleh. They're only good for passing generic functions without losing genericity. When functions are non-generic, interfaces are strictly inferior.

If you were willing to go with a more functional approach instead, life would get easy fast:

type Adder = { Add: int -> int -> int }
let adder() = { Add = fun x y -> x + y }
let adderWithInnerAdder adder = { Add = adder.Add }

Related Questions in F#