Anonymous user
Closures/Value capture: Difference between revisions
no edit summary
imported>Arakov |
imported>Rowsety Moid No edit summary |
||
Line 26:
9
</pre>
=={{header|Acornsoft Lisp}}==
Since this Lisp is dynamically scoped and does not have any built-in closure mechanism, we have to construct one.
<syntaxhighlight lang="lisp">
( (lambda ((a . 1) (b . 2))
(list a b)) )
</syntaxhighlight>
<syntaxhighlight lang="lisp">
(freeze '(a b) '(lambda (c) (list a b c)))
</syntaxhighlight>
would return
<syntaxhighlight lang="lisp">
(lambda (c)
((lambda ((a . 1) (b . 2))
(list a b c))))
</syntaxhighlight>
Here is the definition of <code>freeze</code>:
<syntaxhighlight lang="lisp">
(defun freeze (_fvars_ _lambda-expr_)
(freeze-vars
(mapc cons _fvars_ (mapc eval _fvars_))
(cadr _lambda-expr_)
(cddr _lambda-expr_)))
(defun freeze-vars (bindings lvars lbody)
(list 'lambda lvars
(list (cons 'lambda (cons bindings lbody)))))
</syntaxhighlight>
Once we have <code>freeze</code>, we can create a list of square-returning functions and then call them:
<syntaxhighlight lang="lisp">
(defun range (from to)
(cond ((greaterp from to) '())
(t (cons from (range (add1 from) to)))))
(defun example ()
(mapc '(lambda (f) (f))
(mapc '(lambda (i)
(freeze '(i) '(lambda () (times i i))))
(range 1 10))))
</syntaxhighlight>
{{Out}}
<code>(example)</code> returns
<pre>(1 4 9 16 25 36 49 64 81 100)</pre>
=={{header|Ada}}==
|