Created
February 16, 2014 09:43
-
-
Save omasanori/9031854 to your computer and use it in GitHub Desktop.
A tail-recursive map function with well-known "reverse map" technique.
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
(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