A common thing to do in functional programming is to create, within a (outer) function, a local (inner) function that uses other variables in scope. Let me give you an example. The function countup_from1() uses a local helper function count() to accumulate results recursively. Its argument x is used directly inside count().
Another common thing to do is to make local variables to store the results of expensive computations. Before I give you an example, let’s first define some helper functions.
Using these helpers, we can write a function that returns the max value of an integer vector. Without using local variables to store intermediate results, bad_max() gets very expensive even for small-lengthed input vectors.
We can re-write the function by using a local variable to store the
intermediate result of the expensive recursive step.