In the previous post, I discussed about getting started with Elixir. In this post let’s talk about immutability and pattern matching in Elixir.
In Elixir, like various functional languages, state is immutable. We cannot change the value. However the syntax paves way for reassignment of values to variables. For example in Elixir the following would work fine.
#immutability.exs i = 10 IO.puts i i = 11 IO.puts i
We’ve assigned a value of 10 to the variable i. We then change the value of i to 11. Now in pure functional languages like Erlang, this is an error. We cannot reassign a value to a variable. In Elixir, the compiler creates different versions of i, like i1, i2. It looks like Elixir violates immutability, but it doesn’t. This reassignment is disallowed in several functional languages like Erlang. It’s the developer’s job(or headache) to take care of this reassignment. In Elixir, this is taken care by the compiler itself, making the developer’s job easy.
Pattern matching
We talked about the assignment/re-assignment form in Elixir. What’s interesting in Elixir is the = operator. It’s not an assignment operator. It’s a match operator. We can use the = operator to match a value against a pattern. Let’s look at the code below.
#pattern_matching.exs i = 10 11 = i + 1
The code above works fine., because the match operator =, just compares the left hand side and right hand side. In 11=i+1, the RHS is evaluated and matched with the value on LHS, 11. Say, you write an expression as shown here.
#pattern_matching.exs i = 10 12 = i
The code, 12=i will throw a MatchError as shown below.
Some more examples of pattern matching in Elixir, where we can use lists and tuples are shown here.
{x,y} = {"Hello", "World"} IO.puts "#{x} #{y}" #prints Hello and World numbers = [1,2,3,4] [head|tail] = numbers IO.puts head #prints 1
In the code above, x and y are matched against the tuple {“Hello”,”World”}. We then have a numbers list [1,2,3,4], where the head is matched with the first item and the tail contains the rest of the numbers, ie., 2,3,4.