Skip to content

NestWhileList ​

Like NestWhile, but returns every intermediate value along the way.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageNestWhileList✓
NestWhileList(f, x, test)Every value from xx up to (and including) the first one where testtest fails — the same stopping rule as NestWhile, collected instead of just the last one.
Typed signatures
TypePackageApplies
(any, any, any) -> list<any>combinatoricsalways

Domain: Collections

Details
  • Capped at 4096 applications of ff, same as NestWhile.

Examples

Basic #

halve while even, collecting every intermediate value

live ↗
InNestWhileList(_1⁡↦_1⁡2,96,_1⁡↦_1⁡ mod 2=0)\mathrm{NestWhileList}(\operatorname{\_1}↦\frac{\operatorname{\_1}}{2}, 96, \operatorname{\_1}↦\operatorname{\_1}\bmod2=0)Out[96,48,24,12,6,3]\bigl\lbrack96, 48, 24, 12, 6, 3\bigr\rbrack

Shows each halving step, ending at the odd part

live ↗
InNestWhileList(_1⁡↦_1⁡2,123 456,IsEven)\mathrm{NestWhileList}(\operatorname{\_1}↦\frac{\operatorname{\_1}}{2}, 123\,456, \mathrm{IsEven})Out[123 456,61 728,30 864,15 432,7 716,3 858,1 929]\bigl\lbrack123\,456, 61\,728, 30\,864, 15\,432, 7\,716, 3\,858, 1\,929\bigr\rbrack

The orbit keeps going until the last value is negative, kept symbolic

live ↗
InNestWhileList(ln⁡,100,_1⁡↦_1⁡>0)\mathrm{NestWhileList}(\ln, 100, \operatorname{\_1}↦\operatorname{\_1}\gt0)Out[100,2ln⁡(10),ln⁡(2ln⁡(10)),ln⁡(ln⁡(2ln⁡(10))),ln⁡(ln⁡(ln⁡(2ln⁡(10))))]\bigl\lbrack100, 2\ln(10), \ln(2\ln(10)), \ln(\ln(2\ln(10))), \ln(\ln(\ln(2\ln(10))))\bigr\rbrack
Applications #

A prime gap: no primes from 899899 through 906906, with 907907 next

live ↗
InNestWhileList(_1⁡↦_1⁡+1,899,_1⁡↦¬IsPrime(_1⁡))\mathrm{NestWhileList}(\operatorname{\_1}↦\operatorname{\_1}+1, 899, \operatorname{\_1}↦¬\mathrm{IsPrime}(\operatorname{\_1}))Out[899,900,901,902,903,904,905,906,907]\bigl\lbrack899, 900, 901, 902, 903, 904, 905, 906, 907\bigr\rbrack

Powers of 22 mod 1919 cycle back to 11 after 1818 steps, so 22 is a primitive root

live ↗
InNestWhileList(_1⁡↦2_1⁡ mod 19,2,_1⁡↦_1⁡≠1)\mathrm{NestWhileList}(\operatorname{\_1}↦2\operatorname{\_1}\bmod19, 2, \operatorname{\_1}↦\operatorname{\_1}≠1)Out[2,4,8,16,13,7,14,9,18,17,15,11,3,6,12,5,10,1]\bigl\lbrack2, 4, 8, 16, 13, 7, 14, 9, 18, 17, 15, 11, 3, 6, 12, 5, 10, 1\bigr\rbrack
About
Examples5
Checked againstWolfram Language 5 agree
CrosswalkWolfram Language

See also: NestWhile