给定一个映射程序,我从一个字符串数组映射到一个可区分的联合,我想选择一个特定 DU 类型的实例。我知道会有 0 或 1 个实例。还有比这更聪明的方法吗?
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))
谢谢