我想定义恰好由相同类型支持的类型(例如,FirstName
和LastName
,它们都是string
s),但我希望它们是类型 - 检查,以便我不能错误地混合和匹配它们:
> type FirstName = string;;
type FirstName = string
> type LastName = string;;
type LastName = string
> let n : FirstName = "John";;
val n : FirstName = "John"
//I wish this were caught:
> let l : LastName = n;;
val l : LastName = "John"
有没有办法在F#中做到这一点,没有定义记录类型或某些?
答案 0 :(得分:4)
您可以使用单一案例歧视联盟:
type FirstName =
| FirstName of string
type LastName =
| LastName of string
let n = FirstName "John"
let l: LastName = n // error
有关如何使用这些内容的更多信息,请参阅博文here。
答案 1 :(得分:3)
我相信测量单位可用于字符串,因此您应该可以这样做
[<Measure>]
type FirstName
[<Measure>]
type LastName
let n = "John"<Firstname>
let l:string<LastName> = n