More examples using auxiliary functions →
Let’s look at a couple of more examples in order to get us thinking towards using auxiliary functions and accumulators while writing recursive functions. This would help us write tail-recursive functions which are safer and always a good practice. Note that some of the language compilers do not optimize tail recursions and so be aware of this fact in order not to be surprised when you do not see performance improvements while using tail recursive functions.
Let’s write the standard explode function explode
that explodes a string into a list of characters. i.e., if you pass the string "hello"
, it would explode it and return the list ['h'; 'e'; 'l'; 'l'; 'o']
.
Let’s write another function prime_factors
that would return all the prime factors of an input number n
. Again, we shall use an auxiliary function to do the intermediate computations.
That’s all for today! Hope it was enjoyable.