Skip to content

Instantly share code, notes, and snippets.

@ssboisen
Created September 12, 2013 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssboisen/6533869 to your computer and use it in GitHub Desktop.
Save ssboisen/6533869 to your computer and use it in GitHub Desktop.
Static duck-typing in F#
let inline inTheForest (a: ^a) =
(^a : (member Quack: unit -> unit) (a))
(^a : (member Feathers: unit -> unit) (a))
()
type Duck() =
member x.Quack() = printfn "Quaaaaaack!"
member x.Feathers() = printfn "The duck has white and gray feathers."
type Person() =
member x.Quack() = printfn "The person imitates a duck."
member x.Feathers() = printfn "The person takes a feather from the ground and shows it."
type Dove() =
member x.Feathers() = printfn "The pidgin has white feathers"
inTheForest(new Duck())
inTheForest(new Person())
inTheForest(new Dove()) //Compile error: The type 'Dove' does not support the operator 'Quack'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment