# What is the most efficient way to implement NestPairWhileList[f,expr,test,g]

## Question

NestWhileList[f,x,test] lets you iterate a function until a condition is satisfied, outputting the list of iterated values

    In:= NestWhileList[f,x,test]

Out:= {x,f[x],f[f[x]],f[f[f[x]]], ... }


If the objects produced Nest[f,x,n] are large, and require a lot of storage space, and one only requires some small amount of data captured by g[Nest[f,x,n]], one would like a function

    In:= NestPairWhileList[f,x,test,g]

Out:= {g[x],g[f[x]],g[f[f[x]]],g[f[f[f[x]]]], ... }


is there a simple and efficient way to implement this operation?

This is similar to the relationship between FoldList and FoldPairList, but without requiring the a priori knowledge of the number of iterations.

I can see that one can do

    In:= NestPairWhileList[f_, x_, test_, g_] := g/@NestWhileList[f,x,test]


to produce the correct output, but I do not expect this to be memory efficient as it requires producing the entire output of NestWhileList.

• perhaps nPWL1[f_, x_, test_, g_] := Reap[NestWhileList[Sow@f[##] &, x, test], _, g /@ #2 &][]? – kglr Apr 11 '20 at 1:39
• ... or nPWL2[f_, x_, test_, g_] := Reap[NestWhileList[(Sow[g[#]]; #) &@f[##] &, x, test]][]? – kglr Apr 11 '20 at 1:39

    In:= NestPairWhileList[f_, x_, test_, g_] := ...