Skip to content

Instantly share code, notes, and snippets.

@omasanori
Created February 16, 2014 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omasanori/9031854 to your computer and use it in GitHub Desktop.
Save omasanori/9031854 to your computer and use it in GitHub Desktop.
A tail-recursive map function with well-known "reverse map" technique.
(define (reverse xs)
(define (rev-iter xs ys)
(if (null? xs)
ys
(rev-iter (cdr xs) (cons (car xs) ys)))) ; tail-recursive
(rev-iter xs '()))
(define (foldl f init xs)
(if (null? xs)
init
(foldl f (f init (car xs)) (cdr xs)))) ; tail-recursive too
(define (map f xs)
(reverse
(foldl (lambda (ys x) (cons (f x) ys))
'() xs))) ; thus, it is also tail-recursive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment