First real world example
28 Feb 2014I am not gonna use hello world
example, because that is too simple and boring as well. So lets start with fibonacci series example.
This is our first solution to fibonnaci series. Note the sequence in which
methods are written, they should always be in sequence that can be matched exactly. If we put fib(n)
at top, fib(0)
and fib(1)
will never be matched. Elixir or more generally erlang provides awsome pattern matching and this is an example of that. Whenever fib(0)
is called it will match fib(0)
definition, likewise for others.
But there is a gotcha this program is not safe, try passing negative argument to it, program will hang. So to overcome that we need to guard this program to avaoid negative numbers as parameter. Elixir provides an awsome way to do that as well, called guards
. Let’s rewrite this program to safeguard this from negative numbers.
Note: Execution of fibonacci becomes very slow when number given as input is higher. We will see improved version of it in coming posts.
To make it faster we can cache old summation and just add the new one to it. Let’s look how?
Happy Coding :)