5 ms·
I don't think that I really understood closures until I took Dan Grossman's Coursera course "Programming Languages." In it, we implemented in Racket a simple pr
by mdkess 13y ago
I don't think that I really understood closures until I took Dan Grossman's Coursera course "Programming Languages." In it, we implemented in Racket a simple programming language which included closures, which is the point where it really clicked for me.
In the class, he defines a closure as follows:
"We have said that functions are values, but we have not been precise about what that value exactly is. We
now explain that a function value has two parts, the code for the function (obviously) and the environment
that was current when we created the function. These two parts really do form a “pair” but we put “pair” in
quotation marks because it is not an ML pair, just something with two parts. You cannot access the parts
of the “pair” separately; all you can do is call the function. This call uses both parts because it evaluates
the code part using the environment part.
This “pair” is called a function closure or just closure. The reason is that while the code itself can have free
variables (variables that are not bound inside the code so they need to be bound by some outer environment),
the closure carries with it an environment that provides all these bindings. So the closure overall is “closed”
— it has everything it needs to produce a function result given a function argument."
(section course notes: https://d396qusza40orc.cloudfront.net/proglang/lecture_slides%2Fsection3%2Fsection3sum.pdf https://d396qusza40orc.cloudfront.net/proglang/lecture_slide...)
- city41 13y agoThat's a good concise explanation. The book "High Performance JavaScript"[0] also does a good job explaining how closures work, and includes some visuals that really hammered it home I thought. [0] -- http://shop.oreilly.com/product/9780596802806.do http://shop.oreilly.com/product/9780596802806.do
- christian_fei 13y agothanks for the notes!
- mdkess 13y agoNo problem, thanks for the blog post! I'd highly recommend taking the course - even with a traditional math/cs undergraduate degree from a good school, it was one of the best courses I've ever taken, both in terms of execution and the amount that I learned from it.
- christian_fei 13y agoawesome, will do!
- 32bitkid 13y agoA thing that also really helped me I found in a footnote of Functional Javascript. There the idea of a "free variable" is presented not as free as in freedom, or even free as in beer. But free as in escaped. The variable hitches a ride in the closure and is no longer jailed in its defining scope, and lives on much longer than it normally would. I found that to be a really valuable shift in the way I processed the phrase "free variable".