我在使用以下F sharp函数时遇到问题:
let compare (a:int option list) (b:int option list) =
let r =
if a.Tail = [None] && b.Tail = [None] then
[None]
elif a.Tail = [None] then
[b.Head;None]
elif b.Tail = [None] then
[a.Head; None]
else
if a=b then
a
else
[None]
r
当我使用以下参数运行它时
compare [Some 1] [Some 0]
答案是
[null]
而不是
[None]
有人可以解释原因吗?谢谢!
答案 0 :(得分:1)
实际上,您的compare
函数给出了正确的答案。 fsi打印机将None
打印为null
,这有点误导。
您可以测试None
与不安全的null
值不兼容,如下所示:
let xs = compare [Some 1] [Some 0]
let ys = [None]
let zs = [null]
let test1 = xs = ys;; // true
let test2 = xs = zs;; // error: The type 'int option' does not have 'null' as a proper value
顺便说一下,你的函数有错误的缩进,很难阅读。您可以使用模式匹配来提高其可读性:
let compare (a:int option list) b =
let r =
match a, b with
| [_; None], [_; None] -> [None]
| [_; None], y::_ -> [y; None]
| x::_, [_; None] -> [x; None]
| _ when a = b -> a
| _ -> [None]
r