F# and duck-typing

后端 未结 3 631
一向
一向 2021-01-04 02:30

Let\'s say I defined in F# the following two types:

type Dog = { DogName:string; Age:int }
type Cat = { CatName:string; Age:int }

I was exp

3条回答
  •  生来不讨喜
    2021-01-04 02:59

    Usually what is meant by F# duck-typing is a compile-time polymorphism. Syntax is a little weirder, but you should be able to work it out from the following example -

    module DuckTyping
    
    // Demonstrates F#'s compile-time duck-typing.
    
    type RedDuck =
        { Name : string }
        member this.Quack () = "Red"
    
    type BlueDuck =
        { Name : string }
        member this.Quack () = "Blue"
    
    let inline name this =
        (^a : (member Name : string) this)
    
    let inline quack this =
        (^a : (member Quack : unit -> string) this)
    
    let howard = name { RedDuck.Name = "Howard" }
    let bob = name { BlueDuck.Name = "Bob" }
    let red = quack { RedDuck.Name = "Jim" }
    let blue = quack { BlueDuck.Name = "Fred" }
    

    Remember, this polymorphism only works at compile-time!

提交回复
热议问题