1

我想为值而不是 int 创建类似于枚举的 F# 记录类型。例如,如果我有工会:

type BologneseIngredients = | Spaghetti
                            | Tomatoes
                            | MincedBeef
                            | GrandmasSecretIngredient

我知道意大利面总是30厘米长,西红柿总是红色的。我能做的是有一个“获取元数据”功能:

let getMetadata = function
                    | Spaghetti -> { length: 30.0<cm> }
                    | Tomatoes -> { colour: Color.Red }
                    | _ -> { }

但我真的很想把联合的定义和数据放在一起。有没有很好的方法来做到这一点?

4

2 回答 2

3

您可以将属性添加到您的有区别的工会......

type BologneseIngredients = 
    | Spaghetti
    | Tomatoes
    | MincedBeef
    | GrandmasSecretIngredient

    member x.Color =
        match x with
        | Spaghetti -> Color.AntiqueWhite
        | Tomatoes -> Color.Red
        | MincedBeef -> Color.Firebrick
        | GrandmasSecretIngredient -> Color.Transparent



let foo = Tomatoes

printfn "%A" foo.Color

> Color [Red]
于 2014-07-31T14:49:03.660 回答
2

我的建议:

module Recipes =

    type BologneseIngredients = | Spaghetti
                                | Tomatoes
                                | MincedBeef
                                | GrandmasSecretIngredient

    let length (ind : BologneseIngredients) : float<cm> option =
         match ind with
         | Sphaghetti -> Some 30.0<cm>
         | _ -> None

    // .. or a bit more "metadata"ish
    type Metadata = 
        | Length of float<cm>
        | Color of System.Drawing.Color

    let metadata = 
       function
       | Sphaghetti -> [ Length 30.0<cm ]
       | Tomatoes   -> [ Color System.Drawing.Color.Red ]
       | ...

    let metaLength meta =
       meta |> List.tryPick (function | Length l -> Some l | _ -> None)

    let getLength = metadata >> metaLength
于 2014-07-31T14:59:15.387 回答