-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1-fixed-calculator.rkt
61 lines (43 loc) · 951 Bytes
/
1-fixed-calculator.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
#lang racket
(define (eval-exp exp)
(match exp
[(? number?) exp]
[(list '+ args ...) (apply + (map eval-exp args))]
[(list '- args ...) (apply - (map eval-exp args))]
[(list '* args ...) (apply * (map eval-exp args))]
[(list '/ args ...) (apply / (map eval-exp args))]
[_ (error 'wat (~a exp))]))
(define (evaluate input)
(eval-exp input))
(define (repl)
(printf "> ")
(define input (read))
(unless (eof-object? input)
(define output (evaluate input))
(printf "~a~n" output)
(repl)))
(module+ test
(require rackunit)
(check-equal?
(evaluate '(+ 1 2))
3)
(check-equal?
(evaluate '(+ 1 2 3))
6)
(check-equal?
(evaluate '(- 2 1))
1)
(check-equal?
(evaluate '(* 2 4))
8)
(check-equal?
(evaluate '(/ 8 2))
4)
(check-equal?
(evaluate '(* 2 (+ 1 (- 4 2))))
6)
(check-exn
exn:fail?
(λ ()
(eval '(foo 1 2))))
)