Given a mapping program where I map from an array of strings to a discriminated union, I want to select an instance of a particular DU type. I know that there will be 0 or 1 instances. Is there a smarter way to do it than this?
type thing = { One:int; Two:int; Three:int}
type data = 
    | Alpha of int
    | Bravo of thing
    | Charlie of string
    | Delta of Object
//generate some data
let listData = [
                Alpha(1);
                Alpha(2);
                Bravo( { One = 1; Two = 2; Three = 3 } );
                Charlie("hello");
                Delta("hello again")]
//find the 0 or 1 instances of bravo and return the data as a thing
let result =    listData 
                |开发者_如何学运维> List.map( function | Bravo b -> Some(b) | _ -> None)
                |> List.filter( fun op -> op.IsSome)
                |> (function | [] -> None | h::t -> Some(h.Value))
Thanks
How about
let result =
  listData
  |> List.tryPick (function | Bravo b -> Some b | _ -> None)
List.tryFind will do the trick:
let result = listData
             |> List.tryFind (function | Bravo b -> true | _ -> false)
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论