Skip to main content

functional style - FoldWhile and FoldWhileList


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]]



Comments