我正在尝试编写具有以下签名的 F# 类型:
type Foo = (Distance * Event * Course)
Run Code Online (Sandbox Code Playgroud)
这样你就可以像这样创建一个 Foo :
let bar = (25, Freestyle, LCM)
Run Code Online (Sandbox Code Playgroud)
现在后两部分(事件和课程)很容易——我确定距离也是如此,我只是还不知道——我只是使用了一个可区分的联合。
假设距离的唯一有效值是 [25;50;100],构造距离类型的最佳方法是什么?
我假设目标是轻松访问一个真正的整数值,但将其限制为一定数量的情况。
@Petr 的建议可以正常工作,您只需将枚举值转换为 int。
另一种选择是在 DU 类型的方法中计算值:
type Distance =
TwentyFive | Fifty | Hundred
member this.ToInt() =
match this with
| TwentyFive -> 25
| Fifty -> 50
| Hundred -> 100
Run Code Online (Sandbox Code Playgroud)
或者,如果您想要更强大的语法支持,单例活动模式可能会很好:
type Event = Freestyle | Backstroke
type Distance = TwentyFive | Fifty | Hundred
let (|IntDistance|) d =
match d with
| TwentyFive -> 25
| Fifty -> 50
| Hundred -> 100
let race = (Fifty, Freestyle)
let (IntDistance(dist), evt) = race
printfn "Race info: %d %A" dist evt
match race with
| IntDistance(dist), Freestyle -> ...
| IntDistance(dist), Backstroke -> ...
Run Code Online (Sandbox Code Playgroud)