F#:Seq.forall 奇怪的?
给定 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用“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.以下方法会更实用:
放弃 ResizeArray,转而使用 F# 列表,除非您有特定要求,否则它们通常很有效。
The following approach would be more functional:
Feel comfortable to ditch ResizeArray's in favor of F# lists they are generally efficient unless you have specific requirements.