Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@apg
Created October 25, 2019 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apg/c4e99b9ec88affd1e60669ab8bb7a867 to your computer and use it in GitHub Desktop.
Save apg/c4e99b9ec88affd1e60669ab8bb7a867 to your computer and use it in GitHub Desktop.
;; 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