5
$\begingroup$

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];
 ]
$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$
    – Cassini
    Commented Jul 5, 2019 at 20:30

1 Answer 1

5
$\begingroup$

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    *)
$\endgroup$
1
  • $\begingroup$ beautiful, thank you! $\endgroup$
    – maxgo2
    Commented Aug 5, 2019 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.