Created
August 29, 2013 17:22
-
-
Save anonymous/6380916 to your computer and use it in GitHub Desktop.
Example of extending a type with an interface in F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type MyType() = | |
member x.Stuff = 1 | |
member x.DoStuff() = x.Stuff | |
type IListLike<'T> = | |
abstract Enumerate : unit -> seq<'T> | |
type MyType with | |
member x.DoMore() = x.DoStuff() + 1 // this works | |
interface IListLike<int> with // this doesn't: All implemented interfaces should be declared on the initial declaration of the type | |
member x.Enumerate() = seq { yield 1; yield 2 } | |
[<EntryPoint>] | |
let main argv = | |
let t = new MyType() | |
printfn "%A" (t.DoMore()) | |
System.Console.ReadKey() |> ignore | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818946
Extensions may not define fields, interfaces, abstract slots, inherit declarations, or dispatch slot (interface and override) implementations.
In particular I think the fundamental reason is this: Extension members are compiled as CLI static members with encoded names.
Which obviously can't allow you to augment the type with a new interface.