F# type constraint for record type with specific property

前端 未结 3 1580
失恋的感觉
失恋的感觉 2021-01-17 22:01

I\'m trying to create a generic function which requires of its type argument that it is a record type, and that it has a specific property. Here\'s a sample that generates t

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 23:04

    I don't think there is a way to specify this using static member constraints - static member constraints are fairly restricted and they are mainly an abstraction mechanism that is available in addition to other more usual techniques.

    If I was trying to solve problem like this, I would probably consider using interfaces (this is not always the best way to do this, but without knowing more about your specific situation, it is probably a reasonable default approach):

    type ISetA<'T> = 
      abstract WithA : string -> 'T
    
    type MyRecord = 
      { A : string }
      interface ISetA with
        member x.WithA(a) = { x with A = a }
    

    When implementing the record, you need to add an interface implementation (so you need to do a bit more work than if you could do this using just static member constraints). But then, you are also explicitly saying that this is an intended use for the type...

    The usage is also simpler than when using static constraints:

    let setA (setA:ISetA<_>) = 
      setA.WithA "Hello"
    
    setA { A = "Test" }
    

提交回复
热议问题