Nested Functions
Functions can be defined inside other functions, which are called nested functions or local functions. Nested functions are scoped only within the outer function and invisible to the outside, but can be returned by the outer function and used in a larger scope.
Nested functions can access the outer function's local variables and parameters. This allows the outer function to break down complex logic into multiple internal helper functions without polluting the external namespace.
In the example on the right, processNumbers defines two nested functions sum and average internally, both accessing the parameter numbers. The outer function calls these nested functions and returns the results. This is a common pattern in functional programming.
The main difference between nested functions and lambdas: nested functions have names, can be called recursively, and have syntax closer to ordinary functions; lambdas are more concise and suitable for simple one-time use scenarios.
Try adding a nested function max to find the maximum value in the array and return it as the third element of the tuple.