F # This is an error in Option.map

Given the following code:

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))

Why the result for a and b is:

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

If this is not the case:

[None; Some 3; Some 4; None]
+4
source share
1 answer

Nonerepresented nullin CLR. You can see this while experimenting with FSI:

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

It still works though ::

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

So, [null; Some 3; Some 4; null]coincides with [None; Some 3; Some 4; None]:

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

where ais the value from the OP.

+7
source

Source: https://habr.com/ru/post/1612880/


All Articles