Skip to content

Instantly share code, notes, and snippets.

@apg

apg/map.scm

Created Oct 25, 2019
Embed
What would you like to do?
;; 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