Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #lang racket
- ;;;;;;;;;
- ;; 2.4 ;;
- ;;;;;;;;;
- (define (my-cons x y)
- (lambda (m) (m x y)))
- (define (my-car z)
- (z (lambda (p q) p)))
- ;; Verify (my-car (my-cons x y)) returns x using the substitution model of evaluation.
- ;; (my-car (my-cons x y))
- ;; (my-car (lambda (m) (m x y)))
- ;; ((lambda (m) (m x y)) (lambda (p q) p))
- ;; ((lambda (p q) p) x y)
- ;; x
- (define (my-cdr z)
- (z (lambda (p q) q)))
- (define pr (my-cons 1 2))
- (my-car pr)
- ;; 1
- (my-cdr pr)
- ;; 2
- ;;;;;;;;;
- ;; 2.5 ;;
- ;;;;;;;;;
- (define (my-num-cons a b)
- (* (expt 2 a) (expt 3 b)))
- (define (my-num-car z)
- (if (zero? (remainder z 2))
- (add1 (my-num-car (/ z 2)))
- 0))
- (define (my-num-cdr z)
- (if (zero? (remainder z 3))
- (add1 (my-num-cdr (/ z 3)))
- 0))
- (define num-pr (my-num-cons 2 5))
- (my-num-car num-pr)
- ;; 2
- (my-num-cdr num-pr)
- ;; 5
- ;;;;;;;;;
- ;; 2.6 ;;
- ;;;;;;;;;
- (define (my-compose f g)
- (lambda (x) (f (g x))))
- (define (repeated f n)
- (if (= n 1)
- f
- (my-compose f (repeated f (sub1 n)))))
- ;; church numerals
- (define zero (lambda (f) (lambda (x) x)))
- (define (add-1 n)
- (lambda (f)
- (lambda (x) (f ((n f) x)))))
- ;; Evaluate (add-1 zero) to get a direct definition of one.
- ;; (add-1 zero)
- ;; (lambda (f) (lambda (x) (f ((zero f) x))))
- ;; (lambda (f) (lambda (x) (f x))) ; because (zero f) is the identity function
- ;; (lambda (f) f)
- (define one (lambda (f) f)) ; or (lambda (f) (repeated f 1))
- ;; Evaluate (add-1 one) to get a direct definition of two.
- ;; (add-1 one)
- ;; (lambda (f) (lambda (x) (f ((one f) x))))
- ;; (lambda (f) (lambda (x) (f (f x)))) ; because (one f) is the function f
- ;; (lambda (f) (my-compose f f))
- (define two (lambda (f) (my-compose f f))) ; or (lambda (f) (repeated f 2))
- ;; The church numeral n is the function of f that returns the function of x
- ;; that applies f to x n times. In other words n(f) is f composed with itself n
- ;; times. So church numeral addition should be composition of functions.
- (define (church-numeral->numeral n)
- ((n add1) 0)) ; sends zero to 0, one to 1, two to 2, etc
- (define (church-plus n m)
- (lambda (f)
- (repeated f (+ (church-numeral->numeral n)
- (church-numeral->numeral m)))))
- (church-numeral->numeral zero)
- ;; 0
- (church-numeral->numeral one)
- ;; 1
- (church-numeral->numeral two)
- ;; 2
- (church-numeral->numeral (church-plus one zero))
- ;; 1
- (church-numeral->numeral (church-plus one two))
- ;; 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement