-
Notifications
You must be signed in to change notification settings - Fork 0
/
CALCULATOR DRRACKET.rkt~
98 lines (84 loc) · 3.02 KB
/
CALCULATOR DRRACKET.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#lang racket/gui
; Arithmetic operations
(define (add a b) (+ a b))
(define (subtract a b) (- a b))
(define (multiply a b) (* a b))
(define (divide a b) (if (= b 0) "Error" (/ a b)))
; Function to parse and evaluate the expression
(define (parse-and-eval input)
(define tokens (string-split input))
(if (= (length tokens) 3)
(let ([val1 (string->number (list-ref tokens 0))]
[op (list-ref tokens 1)]
[val2 (string->number (list-ref tokens 2))])
(cond
[(and (number? val1) (number? val2))
(case op
[("+") (add val1 val2)]
[("-") (subtract val1 val2)]
[("*") (multiply val1 val2)]
[("/") (divide val1 val2)]
[else "Error"])]
[else "Error"]))
"Error"))
; GUI components
(define FRAME (new frame% [label "Calculator"]
[width 300]
[height 400]))
(define DISPLAY (new text-field% [parent FRAME]
[label ""]
[min-width 280]
[min-height 50]))
(define (button-callback button-label)
(lambda (button event)
(cond
[(string=? button-label "=")
(let ([result (parse-and-eval (send DISPLAY get-value))])
(send DISPLAY set-value
(if (number? result)
(number->string result)
result)))]
[(string=? button-label "C")
(send DISPLAY set-value "")]
[else
(send DISPLAY set-value
(string-append (send DISPLAY get-value) " " button-label " "))])))
(define BUTTONS
'("1" "2" "3" "+" "4" "5" "6" "-" "7" "8" "9" "*" "C" "0" "=" "/"))
(define PANEL (new vertical-panel% [parent FRAME]
[spacing 10]))
(define (make-button-row panel row-buttons)
(define h-panel (new horizontal-panel% [parent panel] [spacing 10]))
(for ([btn (in-list row-buttons)])
(new button%
[parent h-panel]
[label btn]
[min-width 50]
[min-height 50]
[callback (button-callback btn)])))
(make-button-row PANEL '("7" "8" "9" "/"))
(make-button-row PANEL '("4" "5" "6" "*"))
(make-button-row PANEL '("1" "2" "3" "-"))
(make-button-row PANEL '("C" "0" "=" "+"))
(send FRAME show #t)
; Test function for parse-and-eval
(define (test-parse-and-eval)
(define tests '(("3 + 2" 5)
("10 - 4" 6)
("7 * 3" 21)
("16 / 4" 4)
("5 / 0" "Error")
("abc + 1" "Error")
("1 + 2 + 3" "Error") ; Invalid format
("+" "Error") ; Missing operands
("1 2 +" "Error"))) ; Incorrect format
(for ([test (in-list tests)])
(define input (first test))
(define expected (second test))
(define result (parse-and-eval input))
(if (equal? result expected)
(printf "Test passed for input: ~a\n" input)
(printf "Test failed for input: ~a. Expected: ~a, but got: ~a\n"
input expected result))))
; Run tests
(test-parse-and-eval)