Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment in Elixir

Tags:

erlang

elixir

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?

like image 564
Mahmud Adam Avatar asked Dec 07 '16 04:12

Mahmud Adam


People also ask

What is a variable assignment?

Variable Assignment To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values.

How do you get variable type in Elixir?

There's no direct way to get the type of a variable in Elixir/Erlang. You usually want to know the type of a variable in order to act accordingly; you can use the is_* functions in order to act based on the type of a variable. Learn You Some Erlang has a nice chapter about typing in Erlang (and thus in Elixir).


1 Answers

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.

like image 83
Hynek -Pichi- Vychodil Avatar answered Sep 29 '22 03:09

Hynek -Pichi- Vychodil