在F#中,如何将元数据附加到已区分的联合值上? [英] In F#, How can I attach metadata to discriminated union values?
本文介绍了在F#中,如何将元数据附加到已区分的联合值上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个类似于枚举的东西,它的值是F#记录类型,而不是int.例如,如果我有工会:
I want to create something that's kind of like an enum with an F# record type for a value instead of an int. For example, if I've got the union:
type BologneseIngredients = | Spaghetti
| Tomatoes
| MincedBeef
| GrandmasSecretIngredient
我知道意大利面条总是30厘米长,西红柿总是红色.我所能做的就是拥有获取元数据"功能:
I know that spaghetti is always 30cm long and tomatoes are always red. What I could do is have a 'get metadata' function:
let getMetadata = function
| Spaghetti -> { length: 30.0<cm> }
| Tomatoes -> { colour: Color.Red }
| _ -> { }
但是我真的很想将联合的定义和数据保持在一起.有什么好方法吗?
but I'd really like to keep the definition of the union and the data together. Is there a nice way to do this?
推荐答案
我的建议:
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
这篇关于在F#中,如何将元数据附加到已区分的联合值上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文