Fibonacci in Erlang

We’ve seen the fibonacci example in multiple languages, but none of them purely functional. Erlang is a functional language that is growing in popularity due to the ease in which you can create concurrent programs. It has a number of paradigms that may be foreign to developers that are used to working in scripting or object oriented languages, but rather than a hindrance, things like immutable variables and the lack of loop constructs encourage an elegance in implementation that becomes second nature once you change your mindset.

In this example, we’re using three of these features together to create a very simple version of our fibonacci function.

  • Multiple function clauses – In erlang, you can define a function multiple times – and depending on the arguments passed to the function the correct version of that function is executed.
  • Pattern matching – To determine which function clause is executed, variables declared in the head can be matched against a pattern. In this example, we’re using the same variable name in the first clause for the third and fourth variables. Because variables are immutable, they can only ever equal one value when they are set. That means that when we are looking for “Count” twice in the function head – we are really looking for those variables to contain the same value.
  • Tail recursion – Instead of for or while loops, erlang uses a mechanism called tail recursion. By calling itself multiple times with incremented values, our fibonacci function is in effect executing a loop; and because we have multiple function clauses, we can end the loop when a certain condition is met.

 

Comments are closed.