Recursion: LAMBDA calling LAMBDA
Excel Lambda functions can be used to create custom, reusable functions by giving them a friendly name. This means a custom Lambda function could call itself.
A recursive function is a function that calls itself and self-moves towards an exit condition. Without the exit condition, the function loops continuously unless externally terminated.
Why use recursion?
Some problems can be expressed in an elegant recursive structure. For example the n-th factorial is defined as:
`n! = n (n-1) (n-2) ... 1`
with the termination condition:
`0! = 1`
Recursion example using Lambda
Before we start, Excel provides the FACT function to calculate the factorial of a number. You can use this to compare the results of your own.
This is an example of a recursive function
MyFactorial =LAMBDA(n, IF(n = 0, 1, n * MyFactorial(n-1) ) )
The IF function is used to determine the termination condition. If the termination condition has not been reached, decrement the variable by 1 and call the function again.
To use this function, you have to create it with the Name Manager. See example here.
Questions and Answers
Can I write a recursive Lambda without Function Name Manager?
No. The Lambda function needs to be declared, and that through the Name Manager.
What happens if the Lambda function never reach the exit condition?
If a recursive function never reaches the exit condition it would continue forever. However, in Excel Lambda there is a stack limit of 1024. Thus the recursion limit is set as 1024 divided by (number of Lambda parameters + 1). See this link for details and an example.
Why not use an iterative approach?
An iterative function is a function that loops a section of its code until a condition is met. A recursive function loops by calling itself.
Iteration is more efficient than recursion because you avoid stack call overheads. However, unlike other procedural programming languages, Excel Lambda does not have while loops and for loops.
Hence, if you need to loop, your only option is recursion.
Conclusion
I will be using recursion in my next K-Means clustering post. Ha! And you thought I forgotten about Machine Learning.
See you next year and Happy Holidays from DC-DEN!
Comments
Post a Comment