I'm unexpectedly having a bit of trouble with going from a list of 'a option down to a list containing only the elements that are Some.
My initial attempt was:
let ga = List.filter (fun xx ->
match xx with
| Some(g) -> true
| None -> false) gao
But of course, this result type is still 'a option list. I don't know how to use List.map to condense this, becaus开发者_开发百科e you have to handle all cases in a match statement. I have an ugly solution, but I'm wondering if there is something better.
Ugly:
let rec gOptRemove gdec gacc =
match gdec with
| head :: tail ->
match head with
| Some(a) -> gOptRemove tail (a :: gacc)
| None -> gOptRemove tail gacc
| [] -> gacc
I would prefer to find a non-recursive solution or find out what the standard way is for this kind of thing.
Simply
List.choose id
as in
> [Some 4; None; Some 2; None] |> List.choose id;;
val it : int list = [4; 2]
List.choose
id
Another way is to use the Option module functions to filter out the Options with values and then create a list of the values:
let concreteTypeList =
optionTypeList
|> List.filter (fun v -> Option.isSome v)
|> List.map (fun v -> Option.get v)
精彩评论