如何使用 tryPick 获取序列的第一个元素?

发布于 2024-08-06 02:36:16 字数 288 浏览 4 评论 0原文

我今天尝试使用 Seq.first,编译器表示它已被弃用,转而使用 Seq.tryPick。它表示它应用一个函数并返回第一个返回 Some 的结果。我想我只能说有趣 x -> x!=0 因为我知道第一个在我的情况下会返回 Some,但是在这里放置的正确约束是什么?正确的语法是什么?

为了澄清,我想以以下格式使用它:

let foo(x:seq<int>) =
   x.filter(fun x -> x>0)
   |> Seq.tryPick (??)

I was trying to use Seq.first today, and the compiler says it has been deprecated in favor of Seq.tryPick. It says that it applies a function and returns the first result that returns Some. I guess I can just say fun x -> x!=0 since I know the first one will return Some in my case, but what is the proper constraint to put here? What is the correct syntax?

To clarify, I want to use it in the format:

let foo(x:seq<int>) =
   x.filter(fun x -> x>0)
   |> Seq.tryPick (??)

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

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

发布评论

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

评论(1

无边思念无边月 2024-08-13 02:36:16

关键是“Seq.first”没有返回第一个元素,而是返回与某些“choose”谓词匹配的第一个元素:

let a = [1;2;3]
// two ways to select the first even number (old name, new name)
let r1 = a |> Seq.first (fun x -> if x%2=0 then Some(x) else None) 
let r2 = a |> Seq.tryPick (fun x -> if x%2=0 then Some(x) else None) 

如果您只想要第一个元素,请使用 Seq.head

let r3 = a |> Seq.head 

The key is that 'Seq.first' did not return the first element, rather it returned the first element that matched some 'choose' predicate:

let a = [1;2;3]
// two ways to select the first even number (old name, new name)
let r1 = a |> Seq.first (fun x -> if x%2=0 then Some(x) else None) 
let r2 = a |> Seq.tryPick (fun x -> if x%2=0 then Some(x) else None) 

If you just want the first element, use Seq.head

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