Created
September 2, 2012 02:37
-
-
Save sidharthkuruvila/3594193 to your computer and use it in GitHub Desktop.
An imperative implementation of map in scheme
This file contains hidden or 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
| #lang r5rs | |
| ;Scheme doesn't come with a while loop so we create our own. | |
| (define-syntax while | |
| (syntax-rules (while-loop) | |
| ((while cond stmt1 stmt2 ...) | |
| (letrec ((while-loop | |
| (lambda () | |
| (if cond | |
| (begin stmt1 stmt2 ... (while-loop)) | |
| '())))) | |
| (while-loop))))) | |
| ;Test if to values are not equal | |
| (define (neqv? a b) (not (eqv? a b))) | |
| ;Construct a new list by applying a function on each element | |
| ;of the original list. | |
| (define | |
| (map f l) | |
| (let* ((nl (cons '() l)) | |
| (p nl)) | |
| (while (neqv? l '()) | |
| (set-cdr! p (cons (f (car l)) (cdr l))) | |
| (set! p (cdr p)) | |
| (set! l (cdr l))) | |
| (cdr nl))) | |
| ;Display the squares of the numbers 1 to 10 | |
| (display (map | |
| (lambda (x) (* x x)) | |
| (list 1 2 3 4 5 6 7 8 9 10))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment