FSharp选项和空

时间:2011-12-18 14:12:39

标签: f#

我在使用以下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]

有人可以解释原因吗?谢谢!

1 个答案:

答案 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