使用记录(在函数式编程理论中称为产品类型)来描述由多个属性描述的复杂数据,例如数据库记录或某些模型实体:
type User = { Username : string; IsActive : bool }
type Body = {
Position : Vector2<double<m>>
Mass : double<kg>
Velocity : Vector2<double<m/s>>
}
使用区分联合类型(称为总和类型)来枚举可能的数据值。例如:
type NatNumber =
| One
| Two
| Three
...
type UserStatus =
| Inactive
| Active
| Disabled
type OperationResult<'T> =
| Success of 'T
| Failure of string
请注意,区分联合类型的可能值也是互斥的--一个操作的结果可以是
Success
或
Failure
,但不能同时出现两者。
您可以使用记录类型来编码操作的结果,例如:
type OperationResult<'T> = {
HasSucceeded : bool
ResultValue : 'T
ErrorMessage : string
}
但是,如果操作失败,它的ResultValue
没有意义。因此,在此类型的辨别联合版本上进行模式匹配将如下所示:
match result with
| Success resultValue -> ...
| Failure errorMessage -> ...
如果你对操作类型的记录类型版本进行模式匹配,这样做就没有太多意义:
match result with
| { HasSucceeded = true
| { HasSucceeded = false
看起来冗长笨重,可能效率也不高。我认为当你有这样的感觉时,这可能是提示你使用了错误的工具来完成任务。