I've read a number of articles on the difference between assignment
and binding
, but it hasn't clicked yet (specifically in the context of an imperative language vs one without mutation).
I asked in IRC, and someone mentioned these 2 examples illustrate the difference, but then I had to go and I didn't see the full explanation.
Can someone please explain how/why this works in a detailed way, 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
Binding is used to create a new variable within the current context, while assignment can only change the value of a given variable within the narrowest bound scope.
A binding is the association of a variable name with the variable entity, for example " x refers to the variable declared with class x ". Such bindings depend on the scope, i.e. in every different scope there are different bindings and so the identifier x might refer to different things in different scopes.
I've heard this explanation before and it seems pretty good:
You can think of binding as a label on a suitcase, and assignment as a suitcase.
In other languages, where you have assignment, it is more like putting a value in a suitcase. You actually change value that is in the suitcase and put in a different value.
If you have a suitcase with a value in it, in Elixir, you put a label on it. You can change the label, but the value in the suitcase is still the same.
So, for example with:
iex(1)> x = 1
iex(2)> f = fn -> x end
iex(3)> x = 2
iex(4)> f.()
1
1
in it and you label it x
.1
in it and put it on another suitcase with 2
in it.He will say "1", because the suitcase hasn't changed. Although, you have taken your label off of it and put it on a different suitcase.
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