How to define a scheme function for infix-calculator?
For example when I enter (infix '(2 + 3))
it should evaluate 5
If I enter (infix '(7 - 3)
it should evaluate 4
This can get really complex quite fast. Consider (1 - 2 * 3)
.
If your calculator only supports addition and negation, this is still not trivial. Consider (5 - 5 - 5)
. If you consider the input as left associative, you'll get the correct -5, but if you read it as right associative (which is a common mistake if you parse the expression with some LL parser), you'll get 0.
In order to transform from infix to prefix (which is how you'll calculate your result in Scheme) correctly, you'll usually want to parse the entire input into a parse tree, and once that's done correctly, the rest is, actually, trivial (the tree nodes are operations and the leaves are numbers).
If you only support expressions of two operands, this is easy, just use cadr
to know which operator you got, and apply (maybe using eval
[1]) that operation to the operands
[1] If you do use eval
, note Alex Knauth's comment below.