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

前端 未结 2 1836
抹茶落季
抹茶落季 2020-12-24 00:09

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:

相关标签:
2条回答
  • 2020-12-24 00:39

    Simply

    List.choose id
    

    as in

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

    List.choose

    id

    0 讨论(0)
  • 2020-12-24 01:05

    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)
    
    0 讨论(0)
提交回复
热议问题