F# 判别联合从列表中选择 0 或 1

发布于 2024-09-29 15:28:36 字数 788 浏览 0 评论 0原文

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

从此见与不见 2024-10-06 15:28:36

怎么样

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

How about

let result =
  listData
  |> List.tryPick (function | Bravo b -> Some b | _ -> None)
迎风吟唱 2024-10-06 15:28:36

List.tryFind 可以解决这个问题:

let result = listData
             |> List.tryFind (function | Bravo b -> true | _ -> false)

List.tryFind will do the trick:

let result = listData
             |> List.tryFind (function | Bravo b -> true | _ -> false)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文