I think we are all aware of the assignment operator, yeahh the old =
symbol we all have been using everywhere in programming🤩. You all must have done something like
int x = 10
to assign values to variables, but not today😮.
I've always picked up programming languages quite quickly until I arrived at elixir.
Elixir was my first encounter with functional programming too, so not only the impostor operator but the whole methodologies were quite fascinating.
Ahh so judging things here assignment operator works differently in elixir... but how?
Assignment Operator
So in elixir we have this thing called pattern matching, so lets jump to pattern matching first 😅
Pattern matching
So in layman language, pattern matching is matching the data on the right to the pattern specified on left and binding them if matches (filling variables on left) 🤗 duh.
so back to the assignment operator
when we use the assignment operator somewhat like
x = 10
the compiler checks the left side has a pattern like the right so bam💥let's bind dem 😎.
since we are pattern matching so writing
10 = x
ain't giving us errors either.
and ofc this also works for other data structures too like
[x,y]=[1,2]
but writing
[x,y]=[1,2,3]
is making compiler 😡🤬 coz Pattern(RHS ≠ LHS)
This wouldn't have given us any errors in languages like javascript, it would have just destructured first two values from the list and stored them to x & y.
PS. overwriting variables is a thing so we can reassign values but then our above snippet will raise an exception saying RHS doesn't match LHS hehe i.e ( (MatchError) no match of right hand side value)!
PPS. We can prevent reassignments and make compiler give us error if assigning new value is ≠ old but that's a topic for another day.
Conclusion
So in conclusion all I have to say is that even if we know things from our past experiences. There can always be someone amogthem ඞ who has a new story to tell.
Hope this was interesting ✨
Do Like ❤️, Save 🔖 & Share 📈
Top comments (2)
Interesting! It's a valid match.
LGTM!!