# Replacing loop with functional style

I keep hearing that one should avoid loops in Mathematica and try to write everything in functional style. I've seen few examples of how this done on here, but I could't apply to my problem successfully. It would be great to pick up new ideas of doing it.

Some data for consistency:

X = {1, 2, 3, 4};
History = 1;
SomeVals = {};
SomeFunction[x_, y_] := {x, x + y};


I'm trying to rewrite the following loop into functional style:

For[i = 1, i <= Length@X, i++,
{val, History} = SomeFunction[X[[i]]^2, History];
AppendTo[SomeVals, val];
]

• I'm confused about what you're trying to do. Particularly, I don't understand what you intended History to be used for. The output of SomeVals appears to be {1,4,9,16}, which is simply the square of the elements in X. That's trivial to implement (X^2), but I don't think that's what you intended. Jul 5, 2019 at 20:30

This is precisely the function of FoldPairList:

SomeVals = FoldPairList[SomeFunction[#2^2, #1] &, 1, X]


Let's do this with a more complex example to show that it works in general:

X = Array[x, 10];
History = h;
SomeVals = {};
SomeFunction[x_, y_] := {a[x, y], b[x, y]}

For[i = 1, i <= Length@X,
i++, {val, History} = SomeFunction[X[[i]]^2, History];
AppendTo[SomeVals, val];]

SomeVals == FoldPairList[SomeFunction[#2^2, #1] &, h, X]
(*    True    *)

• beautiful, thank you! Aug 5, 2019 at 7:56