Why is x = x +1 valid in Elixir?

前端 未结 3 2110

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条回答
  •  猫巷女王i
    2021-01-19 01:06

    You can imagine x = x + 1 being rewritten by the compiler to something like x2 = x1 + 1.

    This is pretty close to how it works. It's not a simple index number like I used here, but the concept is the same. The variables seen by the BEAM are immutable, and there is no rebinding going on at that level.

    In Erlang programs, you'll find code like X2 = X1 + 1 all over. There are downsides to both approaches. José Valim made a conscious choice to allow rebinding of variables when he designed Elixir, and he wrote a blog post comparing the two approaches and the different bugs you run the risk of:

    http://blog.plataformatec.com.br/2016/01/comparing-elixir-and-erlang-variables/

提交回复
热议问题