1

给定一个映射程序,我从一个字符串数组映射到一个可区分的联合,我想选择一个特定 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))

谢谢

4

2 回答 2

2

怎么样

let result =
  listData
  |> List.tryPick (function | Bravo b -> Some b | _ -> None)
于 2010-10-29T02:38:16.053 回答
0

List.tryFind 可以解决问题:

let result = listData
             |> List.tryFind (function | Bravo b -> true | _ -> false)
于 2010-10-29T02:40:14.190 回答