なんじゃくにっき

プログラミングの話題中心。

Scala de Design Pattern: Interpreter

 Interpreterパターン。
Wikipediaの例のパクり。
ボーランド記法の式のparse。
これくらいなら意外と簡単にできるもんなんすね。

import scala.collection.mutable.Stack

trait Expression {
def interpret(s: Stack[Int])
}

class Num(number: Int) extends Expression {
def interpret(s: Stack[Int]) = s.push(number)
}

class Plus extends Expression {
def interpret(s: Stack[Int]) = { s.push(s.pop + s.pop) }
}

class Minus extends Expression {
def interpret(s: Stack[Int]) = { s.push(-s.pop + s.pop) }
}

class MultipliedBy extends Expression {
def interpret(s: Stack[Int]) = { s.push(s.pop * s.pop) }
}

class DevidedBy extends Expression {
def interpret(s: Stack[Int]) = {
val x = s.pop
s.push( s.pop / x )
}
}

class Parser(s: String) {
var parseTree = List[Expression]()

for (x <- s.split(" ")) {
x match {
case "+" => parseTree :+= new Plus
case "-" => parseTree :+= new Minus
case "*" => parseTree :+= new MultipliedBy
case "/" => parseTree :+= new DevidedBy
case _ => parseTree :+= new Num(x.toInt)
}
}

def evaluate: Int = {
var context = new Stack[Int]()
parseTree.foreach(_.interpret(context))
context.pop
}
}

object Main {
def main(args: Array[String]) = {
val expression = "42 8 2 / +"
val parser = new Parser(expression)
println(parser.evaluate)
}
}