-
Notifications
You must be signed in to change notification settings - Fork 0
/
6.scm
108 lines (88 loc) · 2.1 KB
/
6.scm
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
;;; -*- buffer-read-only:t -*-
(load "5.scm")
(define (numbered? aexp)
"an expression that contains only numbers"
(cond ((atom? aexp)
(number? aexp))
((eq? '+ (pick 2 aexp))
(and (numbered? (car aexp))
(numbered? (pick 3 aexp))))
((eq? '* (pick 2 aexp))
(and (numbered? (car aexp))
(numbered? (pick 3 aexp))))
((eq? '^ (pick 2 aexp))
(and (numbered? (car aexp))
(numbered? (pick 3 aexp))))))
;;; (numbered? '(1 + (2 * 2)))
(define (numbered? aexp)
"other variant"
(cond ((atom? aexp)
(number? aexp))
(else
;; we already know that aexp is a valid expression
(and (numbered? (car aexp))
(numbered? (pick 3 aexp))))))
;;; (numbered? '(1 + (2 * a)))
(define (value nexp)
"compute the value of a numbered expression. infix notation"
(cond ((atom? nexp)
nexp)
((eq? '+ (pick 2 nexp))
(o+ (value (car nexp))
(value (pick 3 nexp))))
((eq? '* (pick 2 nexp))
(o* (value (car nexp))
(value (pick 3 nexp))))
((eq? '^ (pick 2 nexp))
(o^ (value (car nexp))
(value (pick 3 nexp))))
(else "never reached")))
;; (value '(((10 ^ 2)
;; *
;; (10 + 100))
;; +
;; 3))
(define (1st-sub-exp aexp)
(pick 2 aexp))
(define (2nd-sub-exp aexp)
(pick 3 aexp))
(define (operator aexp)
(car aexp))
(define (value nexp)
"compute the value of a numbered expression. prefix notation"
(cond ((atom? nexp)
nexp)
((eq? '+ (operator nexp))
(o+ (value (1st-sub-exp nexp))
(value (2nd-sub-exp nexp))))
((eq? '* (operator nexp))
(o* (value (1st-sub-exp nexp))
(value (2nd-sub-exp nexp))))
((eq? '^ (operator nexp))
(o^ (value (1st-sub-exp nexp))
(value (2nd-sub-exp nexp))))
(else "never reached")))
;; (value '(+
;; (*
;; (^ 10 2)
;; (+ 10 100))
;; 3))
(define (sero? n)
"numbers represeted as lists (() () () ...)"
(null? n))
;;; (sero? '())
(define (edd1 n)
"add 1"
(cons '() n))
;;; (edd1 '(() ()))
(define (zub1 n)
"subtract 1 in list representation of naturals"
(cdr n))
;;; (zub1 '(() ()))
(define (Op+ n m)
(cond ((sero? m)
n)
(else (edd1 (Op+ n
(zub1 m))))))
;;; (Op+ '(() ())
;;; '(() () ()))