2015-10-23 50 views
4

了一個錯誤:F#這是鑑於以下代碼Option.map

let mapOption (f : ('a -> 'b)) (x : 'a option) = 
    match x with 
    | Some x -> Some(f(x)) 
    | None -> None 

let mapOptions (f : ('a -> 'b)) (xs : 'a option list) : 'b option list = 
    xs 
    |> List.map (fun (x : 'a option) -> mapOption f x) 

let myList = [None; Some 1; Some 2; None] 

let a = myList |> mapOptions (fun x -> x + 2) 

let b = myList |> List.map(fun x-> x |> Option.map(fun y -> y + 2)) 

爲什麼A和B等於結果:

[null; Some 3; Some 4; null]val it : int option list = [null; Some 3; Some 4; null]

豈不是:

[None; Some 3; Some 4; None] 
+5

該行爲(即'None = null')在規範中明確記錄。一些更多的討論在這裏:http://stackoverflow.com/questions/10435052/f-passing-none-to-function-getting-null-as-parameter-value –

回答

7

None由表示CLR中的。你可以看到,通過與FSI試驗:

> [Some 3; None];; 
val it : int option list = [Some 3; null] 

它仍然有效,但::

> [Some 3; None] |> List.choose id;; 
val it : int list = [3] 

所以[null; Some 3; Some 4; null]相同[None; Some 3; Some 4; None]

> a = [None; Some 3; Some 4; None];; 
val it : bool = true 

其中a是價值來自OP。

+0

乾杯,爲我清理這個。 – Stuart