I know that in Mathematica a functional programming style is often more efficient than procedural style programming using For
loops. But the code shown below seems to be an exception, How to explain this?
del[ls_, k_] := Delete[ls, List /@ Range[k, Length@ls, k]]
max = 10^5;
r1 = Range[max];
For[i = 2, i <= Length[r1], i++, r1 = del[r1, i]]; // Timing
r2 = Range[max];
Do[r2 = del[r2, i], {i, 2, Length@r2}]; // Timing
r3 = Fold[del, Range[max], Range[2, max]]; // Timing
r1 == r2 == r3
Out:
{0.031200, Null}
{0.889206, Null}
{0.577204, Null}
True
Catch[Fold[If[#2 < Length[#1], Drop[#1, {#2, Length[#1], #2}], Throw[#1]] &, Range[max], Range[2, max]]]
? $\endgroup$del[ls_, k_Integer] := Drop[ls, {k, Length[ls], k}]; Catch[Fold[If[#2 < Length[#1], del[#1, #2], Throw[#1]] &, Range[max], Range[2, max]]]
$\endgroup$