Mathematica has had NestWhile
and NestWhileList
for some time. But, to date, it has not implemented a built-in FoldWhile
or a FoldWhileList
. So, since these constructs seem useful to me, I have tried to brew my own. Here are my current implementations. Anyone have suggestions on how either of these might be improved. I'd be particularly interested in a variant of FoldWhile
that did not require as much memory as FoldWhileList
.
FoldWhileList[f_, init_, list_, test_, m_, max_] :=
Block[{i = 0},
NestWhileList[(i = i + 1; f[#, Part[list, i]]) &, init, test, m, max]]
and
FoldWhile[f_, init_, list_, test_, m_, max_] :=
Last[FoldWhileList[f, init, list, test, m, max]]
Note: These functions were introduced as built-ins in Version 12.2
m
most recent results. I this is really necessary, then your implementation is likely a way to go, sinceFold
can not be used to implement this. As to the complexity - I don't think most users have to reimplement it themselves - they could as well come to this page and pick whichever implementation they like the most :). $\endgroup$