-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval_postfix.rkt
67 lines (59 loc) · 1.23 KB
/
eval_postfix.rkt
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
#lang racket
(define stack (list -1))
(define (push st x)
(set! stack (cons x st)))
(define (pop st)
(let ((result (car st)))
(set! stack (cdr st))
result))
(define (top st)
(car st)
)
(define operators (list #\+ #\- #\*))
(define input '(1 2 #\+ 4 #\- 4 #\+)) ; '(1 2 #\+ 3 4 #\* 5 #\- #\*)
(define (evalPostfixExpr lis)
(cond
[(empty? lis)
(top stack)
]
[(member (car lis) operators)
(cond
[
(equal? (car lis) #\+)
(begin
(let
([n (+ (pop stack) (pop stack))])
(push stack n)
(evalPostfixExpr (cdr lis))
)
)
]
[
(equal? (car lis) #\*)
(begin
(let
([n (* (pop stack) (pop stack))])
(push stack n)
(evalPostfixExpr (cdr lis))
)
)
]
[
else
(begin
(let
([n (- (- (pop stack) (pop stack)))])
(push stack n)
(evalPostfixExpr (cdr lis))
)
)
]
)
]
[else
(begin
(push stack (car lis))
(evalPostfixExpr (cdr lis))
)
]))
(evalPostfixExpr input)