I 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 :)
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM