How to resolve the algorithm Closures/Value capture step by step in the Acornsoft Lisp programming language
How to resolve the algorithm Closures/Value capture step by step in the Acornsoft Lisp programming language
Table of Contents
Problem Statement
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Closures/Value capture step by step in the Acornsoft Lisp programming language
Source code in the acornsoft programming language
(freeze '(a b) '(lambda (c) (list a b c)))
(lambda (c)
((lambda ((a . 1) (b . 2))
(list a b c))))
( (lambda ((a . 1) (b . 2))
(list a b c)) )
(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)))))
(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))))
You may also check:How to resolve the algorithm Take notes on the command line step by step in the OCaml programming language
You may also check:How to resolve the algorithm Optional parameters step by step in the Clojure programming language
You may also check:How to resolve the algorithm Minimum positive multiple in base 10 using only 0 and 1 step by step in the zkl programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the MySQL programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bead sort step by step in the Arturo programming language