Why is x = x +1 valid in Elixir?

前端 未结 3 2119

Everything I\'ve read about Elixir says that assignment should be thought of as pattern matching. If so then why does x = x + 1 work in Elixir? There is no value of x for wh

3条回答
  •  长情又很酷
    2021-01-19 01:09

    During the pattern matching, the values on the right of the match are assigned to their matched variables on the left:

    iex(1)> {x, y} = {1, 2}
    {1, 2}
    iex(2)> x
    1
    iex(3)> y
    2
    

    On the right hand side, the values of the variables prior to the match are used. On the left, the variables are set.

    You can force the left side to use a variable's value too, with the ^ pin operator:

    iex(4)> x = 1
    1
    iex(5)> ^x = x + 1
    ** (MatchError) no match of right hand side value: 2
    

    This fails because it's equivalent to 1 = 1 + 1, which is the failure condition you were expecting.

提交回复
热议问题