Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of underscore `_` in Elixir

Tags:

elixir

I'm exploring Elixir and came across something rather strange about the underscore. We use it to match any variable and discard it, because Elixir considers it permanently unbound:

iex(38)> _
** (CompileError) iex:38: unbound variable _

But when I assign something to underscore, the value gets echoed the same way it does in the case of normal variable binding:

iex(38)> x = 10
10
iex(39)> _ = 10
10

What does the shell mean by echoing 10 in the second case?

like image 882
ankush981 Avatar asked Dec 24 '22 03:12

ankush981


2 Answers

The = operator returns the value of the RHS after doing the pattern matching. In this case, 10 is ignored as it's assigned to _, but the return value of the whole expression is still 10.

like image 180
Dogbert Avatar answered Dec 29 '22 14:12

Dogbert


Every expression in Elixir will return a value. When pattern matching, it will return the right hand side value.

_ = 10  # return 10 as RHS value

Given that in mind, you can chain the match together.

iex(1)> {date, time} = local_time = :calendar.local_time
{{2016, 8, 9}, {7, 43, 11}}

iex(2)> date
{2016, 8, 9}

iex(3)> time
{7, 43, 11}

iex(4)> local_time
{{2016, 8, 9}, {7, 43, 11}}
like image 41
sbs Avatar answered Dec 29 '22 13:12

sbs