F# 判别联合从列表中选择 0 或 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))
谢谢
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样
How about
List.tryFind 可以解决这个问题:
List.tryFind will do the trick: