-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix_to_postfix.rkt
55 lines (48 loc) · 1.49 KB
/
infix_to_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
#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 math_ops (list #\+ #\- #\*))
(define input (list #\( 1 #\+ 2 #\) #\* #\( 3 #\* 4 #\- 5 #\))) ; (list #\( 1 #\+ 2 #\) #\* #\( 3 #\- 4 #\)) ; ; (list 1 #\+ 2 #\- 3 #\+ 4)
(define (infixToPostfix lis)
(cond
[(empty? lis)
(if (equal? (top stack) -1)
empty ; if top of stack == (
(cons (pop stack) (infixToPostfix lis))
)
]
[(member (car lis) operators)
(if (equal? (car lis) #\) ) ; if current symbol == )
(let ((temp (pop stack)))
(if (equal? temp #\( )
(infixToPostfix (cdr lis)) ; if top of stack == (
(cons temp (infixToPostfix lis)) ; else
)
)
(cond ; else
[
(and (member (top stack) math_ops) ; check for precedence here
(or (equal? (car lis) #\+) (equal? (car lis) #\-)))
(cons (pop stack) (infixToPostfix lis))
]
[
else (begin
(push stack (car lis))
(infixToPostfix (cdr lis))
)
]
)
)
]
[else (cons (car lis)
(infixToPostfix (cdr lis)))]))
(display (infixToPostfix input))