views:

79

answers:

2

Hi all, 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

+2  A: 

How about

let result =
  listData
  |> List.tryPick (function | Bravo b -> Some b | _ -> None)
kvb
A: 

List.tryFind will do the trick:

let result = listData
             |> List.tryFind (function | Bravo b -> true | _ -> false)
dahlbyk
Thanks for the suggestion. I went with List.tryPick instead as that actually gives me a thing option as a result. tryFind gives me back a data option as a result which needs further parsing to actually get the thing vlaue
Dylan