package com.moon.tina
/**
* Created by lin on 2017/5/10.
*/
case class Instruction(name:String,pos:Int)
case class ExecuteInstructions(instructions:List[Instruction],numbers:List[Int])
case class TinaInterpreter() {
var stack:List[Int]=List[Int]()
var answer:Int= _
def loadValue(num:Int): Unit ={
stack=num +:stack
}
def printAnswer(): Unit ={
answer=stack.head
}
def addTwoValues(): Unit ={
val firstNum=stack.head
stack=stack.drop(1)
val secondNum=stack.head
stack=stack.drop(1)
val total=firstNum+secondNum
stack=total+:stack
}
def run(einstructions: ExecuteInstructions): Unit ={
val instructions=einstructions.instructions
val numbers=einstructions.numbers
for(eachStep <- instructions){
if(eachStep.name=="LOAD_VALUE"){
val number=numbers(eachStep.pos)
loadValue(number)
}else if(eachStep.name=="ADD_TWO_VALUES"){
addTwoValues()
}else if(eachStep.name=="PRINT_ANSWER"){
printAnswer()
}
}
}
}
object TinaInterpreter{
def main(args: Array[String]) {
val whatToExecute=ExecuteInstructions(List(
Instruction("LOAD_VALUE",0),
Instruction("LOAD_VALUE",1),
Instruction("ADD_TWO_VALUES",-1),
Instruction("PRINT_ANSWER",-1)
),
List(7,5))
val interpreter=TinaInterpreter()
interpreter.run(whatToExecute)
println(interpreter.stack)
}
}
网友评论