Forum Discussion
LBROWN7
Oct 09, 2023Brass 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...
SergeiBaklan
Oct 13, 2023Diamond Contributor
That could be great workaround. However, performance with SCAN is still not good. Tried poor thunking
SCAN3 = LAMBDA(initial_value, array, function,
LET(
sc, SCAN(LAMBDA(initial_value), array, LAMBDA(a, v, LAMBDA(function(a(), v)))),
n, COLUMNS(sc),
res, LAMBDA(ME, k,
IF( k = 1,
INDEX(sc, 1, 1)(),
HSTACK(ME(ME, k - 1), INDEX(sc, 1, k)() ))),
res(res, n)
)
)
but that gives nothing.
Native function is required. Not sure Microsoft will do it, it looks like all efforts now are concentrated on Python.
LBROWN7
Oct 13, 2023Brass Contributor
HI SergeiBaklan
I added an explicit stack parameter to the recursive scan and that seems to do the trick.
=LAMBDA(initial_value, array, CLAMBDA,
LET(
_00, "Implementation of SCAN in Excel Lambda",
_01, "accumulator must be a scalar or column vector"
vec, TOROW(array),
rec_L, LAMBDA(stack, acc, cindex, rec_LL,
LET(
cvalue, INDEX(vec, 0, cindex),
new_acc, CLAMBDA(acc, cvalue),
new_stack, HSTACK(stack, new_acc),
IF(
cindex = COLUMNS(vec),
new_stack,
rec_LL(new_stack, new_acc, cindex + 1, rec_LL)
)
)
),
tresult, (rec_L(initial_value, initial_value, 1, rec_L)),
MAP(tresult, LAMBDA(v, IF(ISERROR(v), "", v)))
)
)({1}, {2, 3, 4}, LAMBDA(a, b, VSTACK(a, b)))
Probably need to add code to drop the 1st column - but above seems to be moving in the right direction.
1 | 1 | 1 | 1 |
2 | 2 | 2 | |
3 | 3 | ||
4 |
- LBROWN7Oct 14, 2023Brass Contributor
Here is a correct version of the above, with the correct stack initialization. I think this is a valid scan function.
=LAMBDA(initial_value, array, CLAMBDA, LET( _00, "Implementation of SCAN in Excel Lambda", vec, TOROW(array), rec_L, LAMBDA(stack, acc, cindex, rec_LL, LET( cvalue, INDEX(vec, 0, cindex), new_acc, CLAMBDA(acc, cvalue), new_stack, IF(cindex = 1, new_acc, HSTACK(stack, new_acc)), IF(cindex = COLUMNS(vec), new_stack, rec_LL(new_stack, new_acc, cindex + 1, rec_LL)) ) ), tresult, (rec_L("", initial_value, 1, rec_L)), MAP(tresult, LAMBDA(v, IF(ISERROR(v), "", v))) ) )({1, 2}, {2, 3, 4}, LAMBDA(a, b, VSTACK(a, b)))