Вопрос
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?
Решение
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.
Другие советы
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.
Не связан с StackOverflow