FoldWhile
FoldWhile[f,x,{a1,a2,…},test]
returns the first expression f[… f[f[x,a1],a2]…,ak] to which applying test does not yield True.
FoldWhile[f,x,{a1,a2,…},test,m]
supplies the most recent m results as arguments for test at each step.
FoldWhile[f,x,{a1,a2,…},test,m,n]
returns the result after applying f an extra n times after test fails.
FoldWhile[f,x,{a1,a2,…},test,m,-n]
returns the result found when f had been applied n fewer times.
Details
- FoldWhile[f,x,{a1,a2,…},test] returns the last element of FoldWhileList[f,x,{a1,a2,…},test].
- If test[x] does not yield True, FoldWhile[f,x,alist,test] returns x.
- FoldWhile[f,x,alist,test] is equivalent to FoldWhile[f,x,alist,test,1].
- FoldWhile[f,x,alist,test,m] is equivalent to FoldWhile[f,x,alist,test,m,0].
- FoldWhile[f,x,alist,UnsameQ,All] goes on applying f until the same result first appears more than once.
- You can use Throw to exit from FoldWhile before it is finished.
- FoldWhile[f,test][list] is equivalent to FoldWhile[f,list,test].
- FoldWhile[f,test][x,list] is equivalent to FoldWhile[f,x,list,test].
Examples
open allclose allBasic Examples (3)
Scope (9)
Starting with 12, subtract increasing integers while the remainder is still positive:
Use Echo to display the intermediate results:
Display the results of the corresponding tests:
Compute a random walk starting from the origin, and return the first point whose norm is beyond 10:
Fold Cross over a list of random unit vectors while the norm of the result is larger than 0.1:
Add 1/n8 terms until Unequal yields False for two consecutive results in machine arithmetic:
Add random integers to 0 while all results are different, returning the first value that was repeated:
Divide 5! by consecutive positive integers, returning the first non-integer result:
Return the last integer result:
Return the next-to-last integer result:
Abort the computation before it is finished:
Use FoldWhile in operator form:
FoldWhile admits operator forms of three or four arguments when the third and fourth arguments are explicit integers:
Properties & Relations (4)
If test[x] does not yield True, FoldWhile[f,x,alist,test] returns x:
FoldWhile[f,x,alist,test,…] is equivalent to Last[FoldWhileList[f,x,alist,test,…]]:
FoldWhile[f,x,list,True&] is equivalent to Fold[f,x,list]:
FoldWhile[f,x,list,test,m,n] is equivalent to NestWhile[f,x,test,m,Length[list],n] for a function f taking only one argument:
Text
Wolfram Research (2020), FoldWhile, Wolfram Language function, https://reference.wolfram.com/language/ref/FoldWhile.html.
CMS
Wolfram Language. 2020. "FoldWhile." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/FoldWhile.html.
APA
Wolfram Language. (2020). FoldWhile. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/FoldWhile.html