10

I have a question about variable assignment in Elixir. In Erlang, this would raise a no match of right hand side value:

X = 4.
X = 2.

However, it seems perfectly fine in Elixir to assign a value to a variable more than once. I am confused how pattern matching works in Elixir. How does Elixir differentiate between pattern matching and variable assignment? From what I understand, in Erlang, X is an unbound variable so it can be matched with anything, right? But once it is bound, pattern matching only works if it is the same value as X. So does Elixir not share the same concept of unbound variables as Erlang?

2 Answers 2

12

Yes, Elixir doesn't follow the same concept as Erlang in this regard. Elixir tries to be more accessible for developers less familiar with functional programming, especially Ruby developers. According to Pattern matching documentation you have to pin variable:

iex(1)> x=4
4
iex(2)> ^x=2
** (MatchError) no match of right hand side value: 2

Also, note that variables have to start with a lower case in Elixir.

Sign up to request clarification or add additional context in comments.

2 Comments

The blog.plataformatec.com.br/2016/01/… article is a great explanation of the reasoning behind this behaviour.
How is this in explanation instead of a workaround ? Taking Erlang as a start I find this extremely confusing and non-logical. There is no matching in Elixir, they call it rebinding. The link from @michalmuskala is useful, although it also does not explain this in a way that satisfies me to be honest.
0

An attempt to actually answer the question, using knowledge from the link. Elixir does not do matching with the = operator , it does something called rebinding. The code example shows how Elixir can be made to behave like Erlang, which is completely illogical to me as a total new user of the language. I hope to revisit this answer in the future to write something better :).

So Elixir uses pattern matchin when the variable is preceded with a ^ instead of rebinding. My question is : in a big piece of code how those one keep track of first use and use this notation? It would be great if anyone can provide a good answer to that :).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.