Arithmetic evaluation: Difference between revisions

Content added Content deleted
(add mildly cheeky E example)
Line 1,111: Line 1,111:
calcVis((new AST).parse(expression)) ;
calcVis((new AST).parse(expression)) ;
}</lang>
}</lang>

=={{header|E}}==

While the task requirements specify not evaluating using the language's built-in eval, they don't say that you have to write your own ''parser''...

<lang e>def eParser := <elang:syntax.makeEParser>
def LiteralExpr := <elang:evm.makeLiteralExpr>.asType()
def arithEvaluate(expr :String) {
def ast := eParser(expr)
def evalAST(ast) {
return switch (ast) {
match e`@a + @b` { evalAST(a) + evalAST(b) }
match e`@a - @b` { evalAST(a) - evalAST(b) }
match e`@a * @b` { evalAST(a) * evalAST(b) }
match e`@a / @b` { evalAST(a) / evalAST(b) }
match e`-@a` { -(evalAST(a)) }
match l :LiteralExpr { l.getValue() }
}
}
return evalAST(ast)
}</lang>

Parentheses are handled by the parser.

<lang e>? arithEvaluate("1 + 2")
# value: 3

? arithEvaluate("(1 + 2) * 10 / 100")
# value: 0.3

? arithEvaluate("(1 + 2 / 2) * (5 + 5)")
# value: 20.0</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==