-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrd-parser.scm
49 lines (44 loc) · 1.38 KB
/
rd-parser.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
;;; Parses mathematical expressions using Recursive Descent
(define (number stmt)
(cond ((null? stmt)
(valid-expr))
((expect? 'number (car stmt))
(operator (cdr stmt)))
((expect? 'expression-open (car stmt) stmt)
(number (cdr stmt)))
(else (display "Expected a number or expression, got an operator.\n")
(display stmt)
(newline)
#f)))
(define (operator stmt)
(cond ((null? stmt)
(valid-expr))
((expect? 'operator (car stmt))
(number (cdr stmt)))
((expect? 'expression-close (car stmt))
(number (cdr stmt)))
(else (display "Expected an operator, got a number or expression.\n")
(display stmt)
(newline)
#f)))
(define (expect? type sym . args)
(cond ((null? sym)
#t)
((eq? type 'operator)
(member sym '(#\+ #\- #\* #\/ #\% #\= #\! #\^ #\< #\>)))
((eq? type 'number)
(number? sym))
((eq? type 'expression-open)
(and (eq? #\( sym)
(member #\) (car args))))
((eq? type 'expression-close)
(eq? #\) sym))
(else #f)))
(define (parse stmt)
(if (expect? 'number (car stmt))
(number stmt)
(begin
(display "Expecting a number to begin the equation.\n")
#f)))
(define (valid-expr)
#t)