F# and duck-typing

后端 未结 3 630
一向
一向 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 03:05

    You can define an inline function with a member constraint, or go the classic route and use an interface (which would probably be preferred in this case).

    let inline isOld (x:^T) = (^T : (member Age : int) x) >= 65
    

    EDIT

    I just remembered this won't work for record types. Technically their members are fields, although you can amend them with members using with member .... You would have to do that to satisfy an interface anyway.

    For reference, here's how you would implement an interface with a record type:

    type IAging =
      abstract Age : int
    
    type Dog = 
      { DogName : string
        Age : int } 
      interface IAging with
        member this.Age = //could also be `this.Age = this.Age`
          let { DogName = _; Age = age } = this
          age
    

提交回复
热议问题