Best way to condense a list of option type down to only elements that are not none?

Viewed 12059

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, because 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.

2 Answers

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