-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack-calculator.scm
41 lines (35 loc) · 1.09 KB
/
stack-calculator.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
(load "~/.bin/check.scm")
(check-set-mode! 'report-failed)
(define operator
(lambda (expression)
(car expression)))
(define operator?
(lambda (expression)
(define token (car expression))
(or (eq? '+ token)
(eq? '- token)
(eq? '* token)
(eq? '/ token))))
(define calculate
(lambda (expression stack)
(cond ((null? expression) (car stack))
((operator? expression)
(define first-operand (cadr stack))
(define second-operand (car stack))
(define result (eval (list
(operator expression)
first-operand
second-operand)))
(calculate
(cdr expression)
(cons result (cddr stack))))
(else (calculate
(cdr expression)
(cons (car expression) stack))))))
(define rpn
(lamdba (expression)
(if (null? expression)
"there is nothing to calculate!"
(calculate expression '()))))
(check (rpn '()) => )
(check-report)