F#这是Option.map中的错误

时间:2015-10-23 06:08:51

标签: f# f#-3.0 f#-data

给出以下代码:

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]

1 个答案:

答案 0 :(得分:7)

None在CLR中由null表示。你可以通过试验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的值。