Elixir: the little things that tripped me

As many of my readers know I am a very, very old hat in PHP and even older in other imperative languages (three decades and change). Times have changed and I have little doubt functional is the way forward, and I am learning Elixir. Everything I will list is not a criticism of Elixir, simply the language is different. The following presumes you read some tutorials (I strongly recommend Elixir for Programmers) and these are my cliff notes:

  1. Atoms just are. They are not declared anywhere, they do not have a value, they just are, you write :foobar and boom! an atom is born and every time you write another :foobar they match. They do not match with anything else. “foobar” is a binary string and ‘foobar’ is a character list, both of which can be converted into atoms and into each other but they are not atoms.
  2. Atoms often allow for syntactic sugar where you move the colon from the back to the front and then simplify. Check keyword lists and maps.
  3. Returns values, again, just are. When the end of a function is reached, the last expression is the value of the function. (You can’t abort in the middle. Break up your code and remember, guards are your friend.)
  4. Sigils can’t be understood without surrounding code. Like the colon above, which means whatever it is sticking to is an atom but it has a different meaning before and after. The | character means map update in one place and list head / tail separator in another. The %{} construct could come here but deserves its own bullet point.
  5. When pattern matching maps, you can specify only the keys you are asking for. %{a: x, b: y} = %{a: 1, b: 5, c: 6} will happily fill in x and y. So the %{}on the left hand side has a somewhat different meaning.
  6. Everything is an expression, including if andcase. An imperative if reads like “if this is true, do that”. In Elixir, if reads like “if this is true, the result is that”. Assign the value of the entire case to a variable, do not try to assign to a variable that needs to survive outside of the case.
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.