Discriminated union member methods

后端 未结 2 1361
孤独总比滥情好
孤独总比滥情好 2021-02-13 16:28

I want to define a method shared by all members of a discriminated union. Currently I\'ve implemented it like this, but it seems really inelegant- surely there is a better way.

2条回答
  •  广开言路
    2021-02-13 16:55

    What about something like this?

    type AB =
        | A of string
        | B of float
    
        member self.SharedMethod (x : float) =
            match self with
            | A s -> x
            | B f -> f + x
    

    This assumes that you want each variant of your sum type (aka discriminated union) to do something different with the float parameter.

    For the case of A, I just return the original value since there's not much else I can do (since there is no generally useful relationship between string and float that yields a float).

提交回复
热议问题