gpt4 book ai didi

F#:为什么选项类型与可为空类型不兼容?

转载 作者:行者123 更新时间:2023-12-04 01:37:28 24 4
gpt4 key购买 nike

为什么像“int option”这样的选项类型与像“Nullable”这样的可空类型不兼容?

我认为差异有一些语义原因,但我无法弄清楚那是什么。

An option in F# is used when a value may or may not exist. An option has an underlying type and may either hold a value of that type or it may not have a value.



http://msdn.microsoft.com/en-us/library/dd233245%28VS.100%29.aspx

这确实听起来像 Nullable 结构。

最佳答案

因为 System.Nullable<'T> 的运行时表示选择.

Nullable 尝试通过空指针表示值的缺失,并通过指向这些值的指针呈现值。

(new System.Nullable<int>() :> obj) = null
|> printfn "%b" // true

(new System.Nullable<int>(1) :> obj).GetType().Name
|> printfn "%s" // Int32

现在考虑字符串。不幸的是,字符串可以为空。所以这是有效的:
null : string

但现在一个 null运行时值不明确 - 它可以指没有值或存在 null值(value)。因此,.NET 不允许构建 System.Nullable<string> .

对比一下:
(Some (null : string) :> obj).GetType().Name
|> printfn "%s" // Option`1

话虽如此 ,可以定义一个双射:
let optionOfNullable (a : System.Nullable<'T>) = 
if a.HasValue then
Some a.Value
else
None

let nullableOfOption = function
| None -> new System.Nullable<_>()
| Some x -> new System.Nullable<_>(x)

如果您观察类型,这些函数会约束 'T是一个结构体并有一个零参数的构造函数。所以也许 F# 编译器可以公开 .NET 函数接收/返回 Nullable<'T>用它代替 Option<'T where 'T : struct and 'T : (new : unit -> 'T)> , 并在必要时插入转换函数..

关于F#:为什么选项类型与可为空类型不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/947003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com