4 ms·
A closure enables you to keep local state in a functional language. Think of it as an object (a really abused word, I know, but it conveys the idea). So what a
by projectileboy 17y ago
A closure enables you to keep local state in a functional language. Think of it as an object (a really abused word, I know, but it conveys the idea).
So what are the mechanics? Follow me (I'll use Arc):
Lesson 1) A function can return a function:
arc> (def adder-factory () [+ 1 _])
#<procedure: adder-factory>
arc> (= add-1 (adder-factory))
#<procedure>
arc> (add-1 10)
11
Lesson 2) A created function can hang on to information which you pass in:
arc> (def adder-factory (c) [+ c _])
#<procedure: adder-factory>
arc> (= add-17 (adder-factory 17))
#<procedure>
arc> (add-17 13)
30
Lesson 3) The information a function hangs on to can be mutable local state.
arc> (def make-point ((o x 0) (o y 0))
"Constructor for creating point objects"
(let methods (obj
get-x (fn () x)
get-y (fn () y)
set-x [= x _ ]
set-y [= y _ ])
(fn (method . args)
(apply (methods method) args))))
#<procedure: make-point>
arc> (= pt (make-point))
#<procedure>
arc> (= pt (make-point))
#<procedure>
arc> (pt 'get-x)
0
arc> (pt 'set-x 17)
17
arc> (pt 'get-x)
17
And that is a "closure". The name comes from the fact that the scope of the created function "closes over" the local variable.
Helpful or noisy?