Last active
December 27, 2015 14:19
-
-
Save firesofmay/7339883 to your computer and use it in GitHub Desktop.
Alternative procedural representation of pairs.
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html#%_sec_2.1.3
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 racket | |
| ;cons* takes two values and returns a new function | |
| ;which again takes a function f which is called with the closed over values x y | |
| (define (cons* x y) | |
| (lambda (f) (f x y))) | |
| ;car* is a function which takes a function which takes two values | |
| ;but returns just the first value and ignores the second value | |
| ;here _ is a way to say that I do take that argument but I dont care about it. | |
| ;its a way to communicate to the reader of the code not to the compiler | |
| (define (car* f) | |
| (f (lambda (x _) x))) | |
| ;cdr* is a function which takes a function which takes two values | |
| ;but returns just the second value and ignores the first value | |
| (define (cdr* f) | |
| (f (lambda (_ y) y))) | |
| ;This is how (car* (cons* 'a 'b)) expands: | |
| (car* (cons* 'a 'b)) ;=> | |
| (car* (lambda (f) (f 'a 'b))) ;=> | |
| ((lambda (f) (f 'a 'b)) (lambda (x _) x)) ;=> | |
| ((lambda (x _) x) 'a 'b) ;=> | |
| 'a | |
| ;Similary (cdr* (cons* 'a 'b)) expands: | |
| (cdr* (cons* 'a 'b)) ;=> | |
| (cdr* (lambda (f) (f 'a 'b))) ;=> | |
| ((lambda (f) (f 'a 'b)) (lambda (_ y) y)) ;=> | |
| ((lambda (_ y) y) 'a 'b) ;=> | |
| 'b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment