给出以下代码:
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]
答案 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的值。