Created
October 25, 2019 19:23
-
-
Save apg/c4e99b9ec88affd1e60669ab8bb7a867 to your computer and use it in GitHub Desktop.
This file contains 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
;; map, the naive way | |
(define (naive-map f xs) | |
(cond | |
((null? xs) '()) | |
(else (cons (f (car xs)) (map f (cdr xs)))))) | |
(define (tr-map f xs) | |
(define (recurse f xs accum) | |
(cond | |
((null? xs) (reverse accum)) | |
(else | |
(recurse f (cdr xs) (cons (f (car xs)) accum))))) | |
(recurse f xs '())) | |
(define (tr-inline-map f xs) | |
(define head (list #t)) ;; need a non-null to set-cdr! on | |
(define (recurse f xs end) | |
(cond | |
((null? xs) (cdr head)) | |
(else | |
(set-cdr! end (list (f (car xs)))) | |
(recurse f (cdr xs) (cdr end))))) | |
(recurse f xs head)) | |
(define f (lambda (x) (* 2 x))) | |
(define known (naive-map f '(1 2 3 4 5))) | |
(display (equal? known (tr-map f '(1 2 3 4 5)))) | |
(display (equal? known (tr-inline-map f '(1 2 3 4 5)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment