This is a series of problems / challenges around evaluating simple math expressions.
Write a program which can evaluate infix addition operations of non-negative integers.
Example inputs:
1+1
4+13+7853
(and a single number by itself evaluates to itself, i.e. 42 => 42)
Add support for infix subtraction operations.
4-1
12+36-5-19+7
This introduces notion that not all operators have the associativity property. (5-3)-1
is not the same as 5-(3-1)
. Addition is associative (grouping doesn't matter) but subtraction is not associative (grouping does matter).
Add support for multiplication and division.
5+3*2-8/2+1457
This introduces the concept of operator precedence. Multiplication and division take precedence over addition and subtraction.
Note also that multiplication is associative while division is not.
Add support for the unary negation sign.
-5
42*-3
Add support for parenthesis to force operation order.
5-(3-1)
12*(6/2)
5+((4/2)*7)
(((((((1+1)))))))
These problems touch on a variety of fundamental topics in computer science.
Solutions to the problem may be implemented as interpreters or compilers. An interpreter may be interactive (featuring a REPL).
Some of these problems may be solved by implementing a lexer / parser, or by other means, such as translating the expression into reverse-polish notation and implementing a stack evaluator.