F# 将自定义类型转换/转换为原始类型
F# cast / convert custom type to primitive
我已经使用自定义 F# 类型设计我的应用程序域,但现在当我想实际使用数据执行各种任务时,这些自定义类型似乎将成为 PITA...即将值写入 CSV 文件,使用其他依赖基元的库等
例如,我有一个这样的自定义类型(用作其他较大类型的构建块):
type CT32 = CT32 of float
但是这样的代码不起作用:
let x = CT32(1.2)
let y = float x //error: The type "CT32" does not support a conversion...
let z = x.ToString() //writes out the namespace, not the value (1.2)
我尝试使用 box/unbox 和 Convert.ToString() 以及两个 F# 转换运算符,但其中的 none 似乎允许我访问包含的基本原始值我的类型。有没有一种简单的方法来获取自定义类型中的原始值,因为到目前为止,它们令人头疼而不是实际有用。
您的 type CT32
是一个具有一个案例标识符 CT32 of float
的可区分联合。它不是 alias
浮动类型,因此您不能将其转换为浮动类型。
要从中提取值,您可以使用模式匹配(这是最简单的方法)。
type CT32 = CT32 of float
let x = CT32(1.2)
let CT32toFloat = function CT32 x -> x
let y = CT32toFloat x
let z = y.ToString()
作为替代方案(如果您的自定义类型是数字),您可以使用度量单位 https://msdn.microsoft.com/en-us/library/dd233243.aspx 它们没有运行时开销(我相信可区分的联合被编译为 类)但提供编译时类型安全。
添加对 float
的支持很简单:
type CT32 = CT32 of float with
static member op_Explicit x =
match x with CT32 f -> f
let x = CT32(1.2)
let y = float x
您也可以使用 inline deconstruction
,它不需要修改类型本身。
来自 F# for fun and profit 的示例:
type EmailAddress = EmailAddress of string
let email = "foo" |> EmailAddress
let (EmailAddress email') = email // you can now access the email' string value
我已经使用自定义 F# 类型设计我的应用程序域,但现在当我想实际使用数据执行各种任务时,这些自定义类型似乎将成为 PITA...即将值写入 CSV 文件,使用其他依赖基元的库等
例如,我有一个这样的自定义类型(用作其他较大类型的构建块):
type CT32 = CT32 of float
但是这样的代码不起作用:
let x = CT32(1.2)
let y = float x //error: The type "CT32" does not support a conversion...
let z = x.ToString() //writes out the namespace, not the value (1.2)
我尝试使用 box/unbox 和 Convert.ToString() 以及两个 F# 转换运算符,但其中的 none 似乎允许我访问包含的基本原始值我的类型。有没有一种简单的方法来获取自定义类型中的原始值,因为到目前为止,它们令人头疼而不是实际有用。
您的 type CT32
是一个具有一个案例标识符 CT32 of float
的可区分联合。它不是 alias
浮动类型,因此您不能将其转换为浮动类型。
要从中提取值,您可以使用模式匹配(这是最简单的方法)。
type CT32 = CT32 of float
let x = CT32(1.2)
let CT32toFloat = function CT32 x -> x
let y = CT32toFloat x
let z = y.ToString()
作为替代方案(如果您的自定义类型是数字),您可以使用度量单位 https://msdn.microsoft.com/en-us/library/dd233243.aspx 它们没有运行时开销(我相信可区分的联合被编译为 类)但提供编译时类型安全。
添加对 float
的支持很简单:
type CT32 = CT32 of float with
static member op_Explicit x =
match x with CT32 f -> f
let x = CT32(1.2)
let y = float x
您也可以使用 inline deconstruction
,它不需要修改类型本身。
来自 F# for fun and profit 的示例:
type EmailAddress = EmailAddress of string
let email = "foo" |> EmailAddress
let (EmailAddress email') = email // you can now access the email' string value