Created
March 31, 2022 05:53
-
-
Save yanfeng42/59b1b3e49b1ab469191c20fd1cba679f to your computer and use it in GitHub Desktop.
sicp2.22 An iterative version of the answer that is easier to understand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; My answer. | |
#| | |
keypoints: | |
* cache tail node. | |
* call set-cdr! | |
ref: | |
* tips: cons build pairs, not lists. cons build pairs, not lists. ref: https://stackoverflow.com/a/5741668 | |
* https://medium.com/@aleksandrasays/my-other-car-is-a-cdr-3058e6743c15 | |
|# | |
(define (iter things answer tail) | |
(if (null? things) | |
answer | |
(let ((new-tail (list (square (car things))))) | |
(iter (cdr things) | |
(if (null? answer) | |
new-tail | |
(begin | |
(set-cdr! tail new-tail) | |
answer | |
) | |
) | |
new-tail | |
) | |
) | |
) | |
) | |
(trace iter) | |
(define (square-list items) | |
(iter items nil nil) | |
) | |
#| | |
|(iter (1 2 3 4) () ()) | |
|(iter (2 3 4) (1) (1)) | |
|(iter (3 4) (1 4) (4)) | |
|(iter (4) (1 4 9) (9)) | |
|(iter () (1 4 9 16) (16)) | |
|(1 4 9 16) | |
(1 4 9 16) | |
|# | |
(square-list (list 1 2 3 4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment