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?
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
.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With