Forum Discussion
LBROWN7
Oct 09, 2023Copper Contributor
Recursive LAMBDA implementation of Excel's REDUCE function.
Not a question -- just sharing some interesting code. Out of curiosity, I decided to develop an implementation of Excel's REDUCE function as a recursive Excel LAMDA function. I was truly amazed how...
JKPieterse
Oct 10, 2023Silver Contributor
Interesting. Of course using recursion may cause you to hit the recursion limit. Perhaps sooner than hitting limits with REDUCE?
What's that CLAMBDA in your formula?
What's that CLAMBDA in your formula?
- LBROWN7Oct 10, 2023Copper Contributor
Re: your question what is CLAMBDA?recursive LAMBDA PARAMETERS are : [initial_value, array, CLAMBDA ]
recursive LAMBDA ARGUMENTS are: (0, {1,2,3}, LAMBDA(acc,cv, acc+cv) ]Mapping PARAMETERS to ARGUMENTS, we get:
initial_value => 0
array => {1,2,3}
CLAMBDA => LAMBDA(acc,cv, acc+cv)CLAMBDA is a LAMBDA function that tells REDUCE how to combine the previous accumulator with the current_value, to produce the new accumulator. In my example I am just summing [accumulator + current_value] which results in the sum of the inputted array.
Re: Recursion LIMITSYou are correct -- the maximum vector size I was able to use in the recursive function was about 2,700
while in the real Excel REDUCE I could easily use a vector size of 1 million
=REDUCE(0, SEQUENCE(1,1000000,1,1), LAMBDA(acc,cv, acc+cv))
Lastly:
this code demonstrates how one COULD write Excel's REDUCE in as a Recursive Excel LAMBDA function. It in no way implies one should write it this way. However, if you need to do looping where the number of repetitions is unknown, you will likely need to use recursion.
Hope your questions were answered.- SergeiBaklanOct 10, 2023MVP
Just in case, current recursion stake limit is 16384. It is calculated as number of iterations x number of operands. Still not sure how operands are counted. It looks like you have 6 of them.
As for the REDUCE have no idea about the limit. In your sample that's more limit of SEQUENCE by grid size (1 048 576). If less we could have #SPILL! in case of columns, but if more we have #VALUE! in any case.
As for the idea itself it's great to demonstrate lambda self-calling. That was really actual when we have no helper functions and AFE. With them I'm not sure what are the pros of using LAMBDA/ME technique.
- LBROWN7Oct 10, 2023Copper ContributorHi Sergei:
Thanks for the info -- I was totally unaware that there was a way to calculate recursion limits ( aside from empirical testing)
Also, took me a while to figure out what you meant by LAMDA/ME. Going forward I will definately use ME for the recursive function name in the parameter list ( very descriptive)
As to your last comment regarding the utility of LAMDA/ME versus using helper functions. At this point the primary utility of LAMBDA/ME technique in this context is educational,
Thanks for your post.