Last active
October 29, 2019 21:54
-
-
Save chelseatroy/eb945f62db95a8729f27aa2af68e38ea to your computer and use it in GitHub Desktop.
Representing Data Structures
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
; 2.2 Representing data with procedures | |
(define (make-point x y)(cons x y)) | |
(define (x-point point) (car point)) | |
(define (y-point point) (cdr point)) | |
(define a-point (make-point 0 0)) | |
(define b-point (make-point 2 2)) | |
(x-point a-point) | |
(y-point a-point) | |
(define (make-segment start-point end-point)(cons start-point end-point)) | |
(define (start-point segment) (car segment)) | |
(define (end-point segment) (cdr segment)) | |
(define segment (make-segment a-point b-point)) | |
(define (mid-point segment) | |
(make-point (/ (+ (x-point (start-point segment)) (x-point (end-point segment))) 2) | |
(/ (+ (y-point (start-point segment)) (y-point (end-point segment))) 2))) | |
(mid-point segment) | |
; 2.4: Representing data AS procedures | |
(define (24cons x y) | |
(lambda (m) (m x y))) | |
(define (24car z) | |
(z (lambda (p q) p))) | |
(define (24cdr z) | |
(z (lambda (p q) q))) | |
(24car (24cons 2 3)) | |
(24cdr (24cons 2 3)) | |
; 2.5: Another implementation of the data as procedures that yields the same thing (because 2^a * 3^b is a function (unique) in a and b). | |
; The point: the implementation details don't matter. The data is defined by its behavior, not its content or storage or format. | |
(define (25cons a b) | |
(* (expt 2 a) (expt 3 b)) | |
) | |
(define (25car cawns) | |
(if (= 0 (remainder cawns 2)) | |
(+ 1 (25car (/ cawns 2))) | |
0) | |
) | |
(define (25cdr cawns) | |
(if (= 0 (remainder cawns 3)) | |
(+ 1 (25cdr (/ cawns 3))) | |
0) | |
) | |
(define example (25cons 5 7)) ; 69984 | |
(25car example) ; 5 | |
(25cdr example) ; 7 | |
; 2.6: Representing a primitive (numbers) as procedures | |
(define zero (lambda (f) (lambda (x) x))) | |
(define (add-1 n) | |
(lambda (f) (lambda (x) (f ((n f) x))))) | |
(define (inc x) (+ 1 x)) | |
(define one (lambda (f x) (f x))) | |
(define two (lambda (f x) (f (f x)))) | |
(define three (lambda (f x) (f (f (f x))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment