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

a 夏天 提交于 2019-12-08 22:52:28

问题


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.


回答1:


Simply

List.choose id

as in

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

List.choose

id



来源:https://stackoverflow.com/questions/3548532/best-way-to-condense-a-list-of-option-type-down-to-only-elements-that-are-not-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!