Étude 4-3: Non-Tail Recursive Functions

Create a module named powers (no relation to Francis Gary Powers), and write a function named raise/2 which takes parameters X and N and returns the value of XN.

Here’s the information you need to know to write the function:

  • Any number to the power 0 equals 1.
  • Any number to the power 1 is that number itself—that stops the recursion.
  • When N is positive, XN is equal to X times X(N - 1)— there’s your recursion.
  • When N is negative, XN is equal to 1.0 / XN

Note that this function is not tail recursive. Here is some sample output.

1> c(powers).
{ok,powers}
2> powers:raise(5, 1).
5
3> powers:raise(2, 3).
8
4> powers:raise(1.2, 3).
1.728
5> powers:raise(2, 0).
1
6> powers:raise(2, -3).
0.125

See a suggested solution in Appendix A.

Get Études for Erlang now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.