F#:Seq.forall 奇怪的?

发布于 2024-12-21 17:32:04 字数 585 浏览 1 评论 0原文

给定 let ra = ResizeArray; ():

Seq.forall (fun i ->
                    let q = i % 2
                    if 0 = q then ra.Add i
                    true ) <| seq { 1..10 }

如果我这样做,ra.Count 返回5

Seq.forall (fun i ->
                    let q = i % 2
                    if 0 = q then ra.Add i
                    0 = q ) <| seq { 1..10 }

如果我这样做,ra.Count 返回0

那么,除非 lambda 函数的每次迭代都计算为 true,否则实际上函数中的任何代码都不会被执行,或者什么?

这是怎么回事?

Given let ra = ResizeArray<int> ():

Seq.forall (fun i ->
                    let q = i % 2
                    if 0 = q then ra.Add i
                    true ) <| seq { 1..10 }

If I do that, ra.Count returns 5.

Seq.forall (fun i ->
                    let q = i % 2
                    if 0 = q then ra.Add i
                    0 = q ) <| seq { 1..10 }

If I do that, ra.Count returns 0.

So, what, unless every iteration of the lambda function evaluates to true, then effectively none of the code in the function is executed, or what??

What's going on, here?

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

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

发布评论

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

评论(2

书信已泛黄 2024-12-28 17:32:04

您可以使用“false”值来停止 Seq.forall 函数处理更多元素。

由于 1 % 2 = 0 为 false,因此会停止第一次迭代的计算。

You use a value of "false" to cease the Seq.forall function from processing further elements.

Since 1 % 2 = 0 is false, this stops the evaluation on the first iteration.

白鸥掠海 2024-12-28 17:32:04

以下方法会更实用:

let (anyOdds, evens) =
    seq {1..10}
    |> Seq.fold (fun (anyOdds, xs) x ->
        if x % 2 = 0 then
            anyOdds, x :: xs
        else true, xs) (false, [])

放弃 ResizeArray,转而使用 F# 列表,除非您有特定要求,否则它们通常很有效。

The following approach would be more functional:

let (anyOdds, evens) =
    seq {1..10}
    |> Seq.fold (fun (anyOdds, xs) x ->
        if x % 2 = 0 then
            anyOdds, x :: xs
        else true, xs) (false, [])

Feel comfortable to ditch ResizeArray's in favor of F# lists they are generally efficient unless you have specific requirements.

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