DEV Community

Cover image for The = operator is an imposter ඞ
ST1LLWATER
ST1LLWATER

Posted on

The = operator is an imposter ඞ

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
Enter fullscreen mode Exit fullscreen mode

to assign values to variables, but not today😮.

I've always picked up programming languages quite quickly until I arrived at elixir.

Image description

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?

Image description

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

Image description

when we use the assignment operator somewhat like

x = 10
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

ain't giving us errors either.

and ofc this also works for other data structures too like

[x,y]=[1,2]
Enter fullscreen mode Exit fullscreen mode

but writing

[x,y]=[1,2,3]
Enter fullscreen mode Exit fullscreen mode

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)!
Enter fullscreen mode Exit fullscreen mode
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.
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
horngang profile image
HornGang
1 = a = b = 1
Enter fullscreen mode Exit fullscreen mode

Interesting! It's a valid match.

Collapse
 
tanmayvaish profile image
Tanmay Vaish

LGTM!!