开发者

F# discriminated union picking 0 or 1 from a list

开发者 https://www.devze.com 2023-01-22 17:28 出处:网络
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 smar

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消