This is the third and final part of the posts on introducing the Elixir language. Let’s bring in all those things we’ve have discussed so far and solve a simple problem. This is one of those simple exercises that beginners of a functional programming language usually write to get the hang of the syntax.
A simple exercise
Let’s write some code in Elixir to find the sum of all the numbers in a list. And we’ll do that recursively. We’ll define a module say SimpleExercise with a function sum as shown below.
defmodule SimpleExercise do def sum(), do: 0 def sum([head|tail]), do: head + sum(tail) end
The sum function that takes in an empty list returns 0. If we pass in a non-empty list, it’s pattern-matched against head|tail and called recursively. We can invoke the sum function like this.
IO.puts SimpleExercise.sum [1,2,3,4,5]
Here are some interesting features in Elixir that may need your attention.
I have never been a great fan of macros, from my C, C++ days. Elixir’s support for macros did make me feel grumpy, till I understood its real power. Meta-programming in Elixir is achieved through macros. In fact, all the code that we have seen so far in this article, like defining modules using defmodule, defining functions using def are macros.
Elixir introduces the map data structure that was not available in Erlang. Maps are the key-value stores that can have any item as a key. The keys are not ordered as well. The maps data structure was implemented as the keywords structure in the earlier versions of Erlang.
Atom is an interesting data type in Elixir. Simple English words with a colon prefix can be used as identifiers in the form of atoms. For example you can define a variable climate with a value of say winter, without using it as a string. climate = :winter . To quote the Erlang documentation, Atoms are constants where their name is their own value.