Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 730
Tony Peterson Avatar asked Aug 23 '10 14:08

Tony Peterson


1 Answers

Simply

List.choose id 

as in

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

List.choose

id

like image 69
Brian Avatar answered Oct 05 '22 16:10

Brian