Update
I am designing an experimental programming language and the question is wether to include closures or just use first-class-functions. To decide this i need realistic use-cases/examples that show the benefit of closures over first-class-functions. I know that you can achieve everything that you can achieve with one of the two without them, but there are several use-cases for e.g. first-class-functions where the code is easier to read (e.g. shorter or not split up into several classes). E.g:
Ruby:
[1,5,7].map{|x| x*x }
[1,'test',3].select{|x| x.kind_of? Integer}.map{|x| x.to_s }
big_array.each{ |item| puts item }
Without first-class-functions these examples would be a lot more verbose, since you would have to use for-loops or similar things.
Now, what use-cases show the usefulness of closures? Even though i use first-class-functions a lot, i really could not come up with good use-cases for closures. Do you have any good use-cases for closures?
Original Post
I dont get why closures bind to variables and not just to values, e.g.:
Ruby:
x = 5
l = lambda { x }
l.call #=> 5
x = 100
l.call #=> 100
Whats the use in referencing variables instead of just referencing the values stored in the variables at the point of definition of the closure? Like in this example:
Ruby:
x = 5
l = lambda { x }
l.call #=> 5
x = 100
l.call #=> 5, not 100
Are there good use-cases where it is necessary to reference variables instead of just the values of those variables at the point of definition of the closure?