Pages

Tuesday, September 20, 2016

A Powerful Trick

Suppose a function called pow is written in terms of two parameters, number (the first parameter) and exponent (the second parameter). Also suppose that pow should return the value of the first argument passed to the function raised to the power of the second argument passed to the function.

The statements above describe exterior aspects of pow. What might pow look like on the inside? In other words, how might pow be implemented? Or to put the question yet another way, how can we make pow actually do what it should do? What trick shall we use?

Recursion is a powerful type of trick. Here's a particular recursive trick that can be used to (hopefully?) make pow function as it should:

    if (exponent < 0)
        return 1 / pow(number, -1 * exponent);
    else if (exponent == 0)
        return 1;
    else // exponent > 0
        return number * pow(number, exponent - 1); 

Perhaps an English teacher once told you not to define a word in terms of itself. That sort of rule often doesn't apply when defining functions, procedures, methods and the like. You should feel free to at least consider defining a function in terms of itself when using a programming language!