Forum Discussion
Lambda Example: Generate Fibonacci series
SergeiBaklan Good point. I think FIB should probably truncate decimals to integers if entered as parameters to be consistent with other functions. It seems not much change is required to do that because SEQUENCE and INDEX functions already do this (though to be precise one should check values very close to integer as you say.)
=LAMBDA(n,
IF(n<3,
SEQUENCE(n,,0),
LET(b,FIB(n-1),
IF(SEQUENCE(n)<INT(n),b,INDEX(b,n-1)+INDEX(b,n-2)))
))
Viz I found this pretty challenging and don't find recursion very intuitive either. I first laid out the expected results for all input values from 1 to 10 horizontally referring to prior results using spill operator and then substituted LET to make it more efficient.
In case of FIB() - yes, maybe, but the question is more general. How to find the compromise with error handling within lambdas which definitely could reduce the performance. Keep #VALUE! and #N/A as in native functions or add error handling and when. Decision is on case by case basis, I don't see common rule.
Another side effect is rounding which could give an error only on some inner iteration if use recursion, probably it will be bit hard to debug in some cases.
- VizJan 07, 2021Brass Contributor
There may be a better solution but one approach I can think about handling error would be to have Lambda in two layers.
I am just putting the pseudo code here,
MAIN
=Lambda(n, IF(n<>int(n),"Enter integer",FIB(n)))
FIB
=Lambda(n, ..................)
I am new to recursive programming. So, I am not sure if this is the only solution. Perhaps better option exists.
- SergeiBaklanJan 07, 2021Diamond Contributor
The problem is that =n=INT(n) could return TRUE for the first iteration and FALSE on next ones if the difference is around 14th digit.
- lori_mJan 07, 2021Iron Contributor
In this case error handling could be carried out by wrapping in another function as suggested by Viz , the n = INT(n) condition is not iterated then. In general there will be the performance/error propagation considerations you mention so better to avoid adding extra conditions inside recursive functions if possible.