2011-12-18 39 views
1

我有以下的升F功能麻煩:FSharp選項和空

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

比較,您最好不要重新定義它,因爲它已經存在。 – BLUEPIXY 2011-12-18 21:38:54

回答

2

是它顯示的方式,但實際上值是無。 如果你試試這個

Option.isNone ((compare [Some 1] [Some 0]).[0]) ;; 

你得到

val it : bool = true 
1

其實,你compare功能給出了正確的答案。 fsi打印機打印Nonenull,這有點誤導。

您可以測試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