-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator_domain.py
389 lines (339 loc) · 10.8 KB
/
calculator_domain.py
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# ================================================
# Calculator Domain using a state machine
# ================================================
from typing import Optional, Tuple, Union, List, Callable
from enum import Enum
from dataclasses import dataclass, field
# Type aliases for better readability
Number = float
DigitAccumulator = str
class CalculatorState(Enum):
"""
Enumeration for the different states of the calculator.
"""
# Common states
ERROR = 0
# Basic number entry states
ZERO = 1
ACCUMULATOR = 2
COMPUTED = 3
# Expression entry states
START = 4
ENTERING_NUMBER = 5
OPERATOR_INPUT = 6
RESULT = 7
PARENTHESIS_OPEN = 8
FUNCTION_INPUT = 9
class CalculatorInput(Enum):
"""
Represents various inputs for the calculator.
"""
ZERO = "ZERO"
DIGIT = lambda digit: ('DIGIT', digit)
DECIMALSEPARATOR = "DECIMALSEPARATOR"
MATHOP = lambda op: ('MATHOP', op)
EQUALS = "EQUALS"
CLEAR = "CLEAR"
CLEARENTRY = "CLEARENTRY"
BACK = "BACK"
UNDO = "UNDO"
REDO = "REDO"
PARENOPEN = "PARENOPEN"
PARENCLOSE = "PARENCLOSE"
RETURN = "RETURN"
FUNCTION = lambda func: ('FUNCTION', func)
MEMORYSTORE = "MEMORYSTORE"
MEMORYCLEAR = "MEMORYCLEAR"
MEMORYRECALL = "MEMORYRECALL"
def __call__(self, *args):
if callable(self.value):
return self.value(*args)
raise TypeError(f"{self.name} is not callable")
class NonZeroDigit(Enum):
"""
Enumeration for non-zero digits.
ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE = range(1,10)
"""
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
class CalculatorMathOp(Enum):
"""
Enumeration for calculator mathematical operations.
"""
ADD = 1
SUBTRACT = 2
MULTIPLY = 3
DIVIDE = 4
INVERSE = 5
PERCENT = 6
ROOT = 7
CHANGESIGN = 8
MEMORYADD = 9
MEMORYSUBTRACT = 10
class MathFunction(Enum):
"""
Enumeration for mathematical functions.
"""
SQRT = 1
POWER = 2
#
# Type alias for a tuple representing a pending operation and its associated number
PendingOp = Tuple[CalculatorMathOp, Number]
# Expression Tree Data Structure
'''
Expression: This is the base class for all types of expressions. It's defined as
an empty class (a placeholder) from which other expression types inherit.
'''
@dataclass
class Expression:
pass
'''
Value:
--Represents a numerical value in the expression.
--Inherits from Expression.
--Contains a single field value which is a string representation of the number.
'''
@dataclass
class Value(Expression):
value: str
result: bool = field(default=False)
'''
Operator:
--Represents an operator (e.g., +, -, *, /) in the expression.
--Inherits from Expression.
--Contains a single field operator which is a string representing the operator.
'''
@dataclass
class Operator(Expression):
operator: str
'''
Parenthesis:
--Represents an expression enclosed in parentheses.
--Inherits from Expression.
--Contains a single field expression which is another Expression type,
indicating the expression within the parentheses.
'''
@dataclass
class Parenthesis(Expression):
expression: 'Expression'
'''
Function:
--Represents a function application to an argument.
--Inherits from Expression.
--This field holds a callable function that takes a string representation of an
expression and returns a string. This allows you to define any mathematical
function (e.g., square root, sine, cosine) and apply it to the expression.
'''
@dataclass
class Function(Expression):
expression: 'Expression'
function: Callable[[str], str]
'''
Compound:
--Represents a compound expression composed of multiple sub-expressions.
--Inherits from Expression.
--Contains a single field expressions which is a list of Expression objects.
'''
@dataclass
class Compound(Expression):
expressions: List[Expression] = field(default_factory=list)
@dataclass
class Variable(Expression):
name: str
@dataclass
class Exponentiation(Expression):
base: Expression
exponent: Expression
@dataclass
class Fraction(Expression):
numerator: Expression
denominator: Expression
@dataclass
class Subscript(Expression):
base: Expression
subscript: Expression
@dataclass
class Superscript(Expression):
base: Expression
superscript: Expression
@dataclass
class NthRoot(Expression):
radicand: Expression
degree: Expression
@dataclass
class Matrix(Expression):
rows: List[List[Expression]]
@dataclass
class Equation(Expression):
lhs: Expression
rhs: Expression
@dataclass
class Conditional(Expression):
condition: Expression
true_expr: Expression
false_expr: Expression
# Catamorphism to Traverse the Expression Tree
def evaluate_expression(expr: Expression) -> str:
if isinstance(expr, Value) and expr.result == False:
return expr.value
elif isinstance(expr, Value) and expr.result == True:
return f"\\\\class{{result-box}}{{{expr.value}}}"
elif isinstance(expr, Variable):
return expr.name
elif isinstance(expr, Operator):
return expr.operator
elif isinstance(expr, Parenthesis):
return f"({evaluate_expression(expr.expression)})"
elif isinstance(expr, Function):
return expr.function(f"{evaluate_expression(expr.expression)}")
elif isinstance(expr, Compound):
return "".join(evaluate_expression(e) for e in expr.expressions)
elif isinstance(expr, Exponentiation):
return f"{evaluate_expression(expr.base)}^{evaluate_expression(expr.exponent)}"
elif isinstance(expr, Fraction):
return f"({evaluate_expression(expr.numerator)}/{evaluate_expression(expr.denominator)})"
elif isinstance(expr, Subscript):
return f"{evaluate_expression(expr.base)}_{evaluate_expression(expr.subscript)}"
elif isinstance(expr, Superscript):
return f"{evaluate_expression(expr.base)}^{evaluate_expression(expr.superscript)}"
elif isinstance(expr, NthRoot):
return f"√[{evaluate_expression(expr.degree)}]{evaluate_expression(expr.radicand)}"
elif isinstance(expr, Matrix):
return "[" + "; ".join(["[" + ", ".join(evaluate_expression(e) for e in row) + "]" for row in expr.rows]) + "]"
elif isinstance(expr, Equation):
return f"{evaluate_expression(expr.lhs)} = {evaluate_expression(expr.rhs)}"
elif isinstance(expr, Conditional):
return f"if {evaluate_expression(expr.condition)} then {evaluate_expression(expr.true_expr)} else {evaluate_expression(expr.false_expr)}"
else:
return ""
#raise ValueError("Unknown Expression Type")
class MathOperationError(Enum):
"""
Constants for various math operation errors.
"""
DIVIDEBYZERO = "Divide by Zero Error"
MATHDOMAINERROR = "Math Domain Error"
@dataclass
class MathOperationResult:
"""
Represents the result of a math operation, including success and failure cases.
Attributes:
success (Optional[Number]): The result of the operation if successful.
failure (Optional[MathOperationError]): The error if the operation failed.
"""
success: Optional[Number] = None
failure: Optional[MathOperationError] = None
def __str__(self):
return f"MathOperationResult(success='{self.success}', failure='{self.failure}')"
# Computation States
@dataclass
class AccumulatorStateData:
"""
State data for the accumulator phase of the calculator.
Attributes:
digits (str): The digits accumulated.
pending_op (Optional[PendingOp]): The pending operation.
memory (str): The memory state.
"""
digits: str = ""
pending_op: Optional[PendingOp] = None
memory: str = ""
def __str__(self):
return f"AccumulatorStateData(digits='{self.digits}', pending_op={self.pending_op}, memory='{self.memory}')"
@dataclass
class ComputedStateData:
"""
State data for the computed phase of the calculator.
Attributes:
display_number (float): The number to display.
pending_op (Optional[PendingOp]): The pending operation.
memory (str): The memory state.
"""
display_number: float = 0.0
pending_op: Optional[PendingOp] = None
memory: str = ""
def __str__(self):
return f"ComputedStateData(display_number={self.display_number}, pending_op={self.pending_op}, memory='{self.memory}')"
@dataclass
class ErrorStateData:
"""
State data for the error phase of the calculator.
Attributes:
error (MathOperationError): The error encountered.
memory (str): The memory state.
"""
math_error: Optional[MathOperationError] = None
# additional error types as needed
memory: str = ""
def __str__(self):
return f"ErrorStateData(math_error={self.math_error}, memory='{self.memory}')"
@dataclass
class ZeroStateData:
"""
State data for the zero phase of the calculator.
Attributes:
pending_op (Optional[PendingOp]): The pending operation.
memory (str): The memory state.
"""
pending_op: Optional[PendingOp] = None
memory: str = ""
def __str__(self):
return f"ZeroStateData(pending_op={self.pending_op}, memory='{self.memory}')"
####### Expression States#######
@dataclass
class StartStateData:
memory: str = " "
@dataclass
class NumberInputStateData:
current_value: str
expression_tree: Compound
memory: str = " "
stack: List[str] = field(default_factory=list)
@dataclass
class OperatorInputStateData:
previous_value: str
operator: str
current_value: str
expression_tree: Compound
memory: str = " "
stack: List[str] = field(default_factory=list)
@dataclass
class ResultStateData:
result: str
memory: str = " "
history: List[str] = field(default_factory=list) # ToDo
@dataclass
class ParenthesisOpenStateData:
inner_expression: str
expression_tree: Compound
memory: str = " "
stack: List[str] = field(default_factory=list)
@dataclass
class FunctionInputStateData:
current_value: str
expression_tree: Compound
memory: str = " "
stack: List[str] = field(default_factory=list)
ExpressionStateData = Union[
StartStateData,
NumberInputStateData,
OperatorInputStateData,
ResultStateData,
ParenthesisOpenStateData,
FunctionInputStateData]
# Type alias for a tuple representing an expression state and the input recieved.
@dataclass
class ExpressionStateHistoryItem:
recent_state_data: ExpressionStateData
current_input: CalculatorInput
widget_ID: int
def __str__(self):
state_type_name = type(self.recent_state_data).__name__
return f"recent state data -> {state_type_name} with current input -> {self.current_input} on mathquill widget No. {self.widget_ID}"