aboutsummaryrefslogtreecommitdiff
path: root/SICP/ex2-4.scm
blob: bfc3b645bb7ecf9d3df2cd474db4df912515626c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
(define (cons x y)
  (define (dispatch m)
    (cond ((= m 0) x)
          ((= m 1) y)
          (else
            (error "Argument not 0 or 1:
                   CONS" m))))
  dispatch)

(define (car z) (z 0))
(define (cdr z) (z 1))

(define pair (cons 111 2))

(car pair)

;Exercise 2.4
(define (cons x y)
  (lambda (m) (m x y)))

(define (car z)
  (z (lambda (p q) p)))
(define (cdr z)
  (z (lambda (p q) q)))

(cdr (cons 1 2))

;Exercise 2.5
(define (cons x y) (* (pow 2 x) (pow 3 y)))

(define (pow x y)
  (if (= y 0) 
    1
  (* x (pow x (- y 1)))))


(define (car z)
 (if (not (= (modulo z 2) 0))
    0
    (+ (car (/ z 2)) 1)))
(define (cdr z)
  (if (not (= (modulo z 3) 0))
    0
    (+ (cdr (/ z 3)) 1)))

(car (cons 10 2))
(cdr (cons 1 119))

;Exercise 2.6

(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
  (lambda (f) (lambda (x) (f ((n f) x)))))

(define one (lambda(f) (lambda (x) (f x))))

(= one (add-1 zero))