Recursion
Last updated
Last updated
Assume that all we have is addition and subtraction but need to define multiplications. How would you do? You will have to use recursion and you solve it by first describing the multiplication functions by words.
The product of and is: 0 if is equal to 0, otherwise the product is plus the product of and .
Once you have written down the definition, the coding is simple.
Implement the following arithmetic functions and save them in a file recursion.ex
. In order not to create any conflicts with built-in function, you will have to call your functions something different i.e. prod
instead of product
etc.
When you implement them write a small documentation. For more information regarding documenting Elixir check the the following documentation.
prod
: complete the above implementation of product
prod
: change the above definition so that it also works for negative numbers
power
: implement the power function for non-negative exponents
qpower
: use the two functions div and rem to implement a faster version of the power function by dividing the exponent by two in each recursive step (what must be done if the exponent is odd?)
There are several ways of expressing the same thing in Elixir . The function product could be writen using the cond-expression below. We would then use arithmetic comparisions that would evaluate to true
or false
.
We could also divide the alternatives into different clauses as in the code below.
This should be read: if we call product, and the first argument matches 0, then the result is .... If we can not use the first clause then we try the second clause.
Sometimes the code becomes easier to understand, especially if we have many conditions that should be tested. Remember though that the clauses of a function need to be after each other. You can not spread the clauses around in a program.
Try some more complex functions, for example the Fibonacci function:
Write simple Fibonacci function fib/1 and do some performance measurements.
You can also give the Ackermann function a try:
This looks like an innocent little function but don't try too high numbers.
The Fibonacci sequence is the sequence . The two first numbers are 0 and 1 and the following numbers are calculated by adding the two previous number. To calculate the Fibonacci value for n , all you have to do is find the Fibonacci number for n-1 and n-2 and then add them together.
Find an arithmetic expression that almost describes the computation time for . Can you justify this arithmetic expression by looking at the definition of the function? How large Fibonacci number do you think you can compute if you start now and let your machine run until tomorrow? First make a guess, don't try to do the calculation in your head just make a wild guess, then try to estimate how long time that would take using your arithmetic function, would you be able to make it?