Closure is "a class with one method, apply" (as Guy Steele succinctly noted on a mailing list I lost reference to) or to put it in another way, it is "a function that can access its outside lexical environment". See http://en.wikipedia.org/wiki/Lexical_closure for more elaborate description.
I would say that the difference between the class and function interpretations is at the syntax level, not in semantics.
faq has some explanation regarding closures in picoLisp.
As closures are useful in various situations, lets discuss practical options how to use them in picoLisp. Most of the summary here originated from mailing list.
Question: Is there a better way of achieving the following?
(let @S '((I . 0)) (def 'count1 (fill '(() (job '@S (inc 'I))))) (def 'reset (fill '(() (job '@S (zero I))))))
The two functions are closed over (share) the same variable I.
(count1) => 1 (count1) => 2 (reset) => 0 (count1) => 1
Answer 1: With a little trick, you could also use it here:
(let I '(0) (def 'count1 (curry (I) () (inc I))) (def 'reset (curry (I) () (set I 0))) )
Answer 2: There is a kind of middle way between our two solutions:
(let @S '((I . 0)) (def 'count1 (curry (@S) () (job '@S (inc 'I)))) (def 'reset (curryrlog: can't exec (@S) () (job '@S (zero I)))) )
BTW, all three solutions have in common that they depend on a shared data structure (a cell (I . 0) or (0)). If the 'let' is going to be used within some other function (instead of the top level here), it should better be
(let @S (list (cons 'I 0))
or
(let I (cons 0)
to use a locally encapsulated cell.
...once the things inside the closures get complicated, it might be worth using objects to get better code factoring:
(class +Counter) # i (dm T () (=: i 0) ) (dm count> () (inc (:: i)) ) (dm reset> () (=: i 0) ) (let @C (list (cons 'C (new '(+Counter)))) (def 'count (curry (@C) () (job '@C (count> C)))) (def 'reset (curry (@C) () (job '@C (reset> C)))) )
Or using objects directly so that I can have many independent counters...
This page is linked from: non-blocking
Revisions: View source XHTMLV | RSSV
picoWiki pages can be edited by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively