在 F# 中,有没有办法为基本类型定义类型检查的别名?
In F#, is there a way to define a type-checked alias for a primitive type?
我想定义恰好由相同类型支持的类型(例如,FirstName
和 LastName
,它们都是 string
),但我希望它们进行类型检查,这样我就不会错误地混合和匹配它们:
> 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# 中执行此操作,而不是定义记录类型或类似的类型?
您可以使用单案例区分联合:
type FirstName =
| FirstName of string
type LastName =
| LastName of string
let n = FirstName "John"
let l: LastName = n // error
有关如何使用它们的更多信息,请参阅博客 post here。
我相信度量单位可以用于字符串,所以你应该能够做到这一点
[<Measure>]
type FirstName
[<Measure>]
type LastName
let n = "John"<Firstname>
let l:string<LastName> = n
我想定义恰好由相同类型支持的类型(例如,FirstName
和 LastName
,它们都是 string
),但我希望它们进行类型检查,这样我就不会错误地混合和匹配它们:
> 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# 中执行此操作,而不是定义记录类型或类似的类型?
您可以使用单案例区分联合:
type FirstName =
| FirstName of string
type LastName =
| LastName of string
let n = FirstName "John"
let l: LastName = n // error
有关如何使用它们的更多信息,请参阅博客 post here。
我相信度量单位可以用于字符串,所以你应该能够做到这一点
[<Measure>]
type FirstName
[<Measure>]
type LastName
let n = "John"<Firstname>
let l:string<LastName> = n