I saw a piece of code from the website http://www.ccs.neu.edu/home/shivers/newstyle.html:
> (defun element-generator ()
(let ((state '(() . (list of elements to be generated)))) ;() sentinel.
(let ((ans (cadr state))) ;pick off the first element
(rplacd state (cddr state)) ;smash the cons
ans)))
ELEMENT-GENERATOR
> (element-generator)
LIST
> (element-generator)
OF
> (element-generator)
ELEMENTS
> (element-generator)
TO
> (element-generator)
BE
> (element-generator)
GENERATED
I don't understand how the function remembers the state. Isn't state
redefined to the whole list each time the function runs? And why the two layers of let
(which is necessary)? It'd be appreciated if someone is able to explain how this function works.
The value of state
in (let ((state '(() . (list of elements to be generated)))) ...)
is a quoted literal, and it is being modified (which, as explained in this answer is undefined behavior). This behavior has been discussed other questions, such as:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With