Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding vs Assignment

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
like image 781
Tallboy Avatar asked Jan 04 '18 17:01

Tallboy


People also ask

What is binding assignment?

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.

What is binding in variable?

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.


1 Answers

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. You have a suitcase with 1 in it and you label it x.
  2. Then you say, "Here, Mr. Function, I want you to tell me what is in this suitcase when I call you."
  3. Then, you take the label off of the suitcase with 1 in it and put it on another suitcase with 2 in it.
  4. Then you say "Hey, Mr. Function, what is in that suitcase?"

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.

like image 73
ryanwinchester Avatar answered Sep 21 '22 13:09

ryanwinchester