Assignment Link

I read a series of articles on the difference between assignmentand binding, but it has not yet been pressed (especially in the context of an imperative language and without mutation).

I asked at the IRC, and someone mentioned these 2 examples, illustrates the difference, but then I had to go, and I did not see a full explanation.

Can someone explain how / why this works in detail to help illustrate the difference?

ruby

x = 1; f = lambda { x }; x = 2; f.call
#=> 2

Elixir

x = 1; f = fn -> x end; x = 2; f.()
#=> 1
+4
source share
5 answers

I have heard this explanation before, and it looks pretty good:

You can think of binding as a label on a suitcase, and assignment as a suitcase.

, , , . , , .

, Elixir, . , .

, :

iex(1)> x = 1
iex(2)> f = fn -> x end
iex(3)> x = 2
iex(4)> f.()
1
  • 1 , x.
  • : ", - , , , , ".
  • 1 2 .
  • : ", - , ?"

"1", . , .

+2

. Elixir " " . , . Ruby , , , . Elixir , ( ), .

Erlang, "" , , , "". , X, , . ( Erlang, .)

+1

- AST, / ,/-.

ruby. Ruby AST , RubyParser :

> require 'ruby_parser'
> RubyParser.new.parse("x = 1; f = -> {x}; x = 2; f.()").inspect

#=> "s(:block, s(:lasgn, :x, s(:lit, 1)), 
#    s(:lasgn, :f, s(:iter, s(:call, nil, :lambda), 0, s(:lvar, :x))),
#    s(:lasgn, :x, s(:lit, 2)), s(:call, s(:lvar, :f), :call))"

, , node : proc x. , Ruby , x. proc x 2. , proc 2.

Elixir.

iex|1 โ–ถ quote do
...|1 โ–ถ   x = 1
...|1 โ–ถ   f = fn -> x end
...|1 โ–ถ   x = 2
...|1 โ–ถ   f.()
...|1 โ–ถ end

#โ‡’ {:__block__, [],
# [
#   {:=, [], [{:x, [], Elixir}, 1]},
#   {:=, [], [{:f, [], Elixir}, {:fn, [], [{:->, [], [[], {:x, [], Elixir}]}]}]},
#   {:=, [], [{:x, [], Elixir}, 2]},
#   {{:., [], [{:f, [], Elixir}]}, [], []}
# ]}

node - . x, x . , fn -> not_x end , - proc, .

, Ruby proc, Elixir . , , .

+1

, , , "" ""; , , .

, , "" "". ; - "", , . , Erlang . (, , , ?)

Elixir:

iex> x = 1
iex> 1 = x

. , - . . . = Elixir ( Erlang): a = b , ; RHO, ; LHO RHO, LHO .

Ruby . ( ) ( .)

+1

, , , , . ML-, :

let x = 3 in
   let y = 5 in
       x + y

val it : int = 8

let... in, , , let x = 3 , in. , let y = 5 x + y, :

let x = 3 in
   let f () =
       x + 5
   let x = 4 in
       f()

val it : int = 8

The result is still 8, although we have a binding let x = 4above the call f(). This is due to the fact that fhe himself was connected in the field of binding let x = 3.

Assignment in operator-based languages โ€‹โ€‹is different, because the assigned variables are not tied to a specific expression, they are effectively "global" for any block of code in which they are located, so reassigning the value of a variable changes the result of the evaluation using the same variable.

0
source

Source: https://habr.com/ru/post/1691751/


All Articles