Arithmetic evaluation: Difference between revisions

Content added Content deleted
(→‎{{header|Scala}}: Added simpler example, which doesn't follow all requirements)
(→‎{{header|Scala}}: On a second thought, remove that code, for copyright reasons)
Line 1,309: Line 1,309:
</pre>
</pre>


This example was made rather more complex by the requirement of generating an AST tree. Here is an arithmetic evaluator using the very same library, but not bounded by that requirement:
This example was made rather more complex by the requirement of generating an AST tree. With a Scala distribution there are many examples of arithmetic parsers, as small as half a dozen lines.

<lang scala>/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2006-2010, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */

package examples.parsing

import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.parsing.combinator.syntactical.StdTokenParsers

/** Parse and evaluate a numeric expression as a sequence of terms, separated by + or -
* a term is a sequence of factors, separated by * or /
* a factor is a parenthesized expression or a number
*
* @author Adriaan Moors
*/
object arithmeticParser extends StdTokenParsers {
type Tokens = StdLexical ; val lexical = new StdLexical
lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")

lazy val expr = term*("+" ^^^ {(x: int, y: int) => x + y} | "-" ^^^ {(x: int, y: int) => x - y})
lazy val term = factor*("*" ^^^ {(x: int, y: int) => x * y} | "/" ^^^ {(x: int, y: int) => x / y})
lazy val factor: Parser[int] = "(" ~> expr <~ ")" | numericLit ^^ (_.toInt)
def main(args: Array[String]) {
println(
if (args.length == 1) {
expr(new lexical.Scanner(args(0)))
}
else
"usage: scala examples.parsing.arithmeticParser <expr-string>"
)
}
}</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==