问题描述
我正在构建一个堆栈机模拟器,并且在弄清楚如何在Load和Store情况下更新环境/映射时遇到了麻烦。我的目标是弄清楚如何更新地图,并反复进行迭代以获取用于更新地图的正确值。
case class LoadI(s: String) extends StackMachineInstruction
case class StoreI(s: String) extends StackMachineInstruction
def emulateSingleInstruction(stack: List[Double],env: Map[String,Double],ins: StackMachineInstruction): (List[Double],Map[String,Double]) = {
ins match{
case AddI => stack match{
case i1 :: i2 :: tail => (i1 + i2 :: tail,env)
case _ => throw new IllegalArgumentException()
}
case PushI(f) => (f :: stack,env)
//broken
case LoadI(s) => stack match {
case Nil => throw new IllegalArgumentException()
case i1 :: tail => (tail,env) match {
case (top,env) => (top,env + s -> top ) // Not clear on how to update an environment
}
}
//broken
case StoreI(s) => stack match {
case Nil => throw new IllegalArgumentException()
case i1 :: tail => // Need to take the value that s maps to in the environment. Let the value be v. Push v onto the top of the stack.
}
case PopI => stack match{
case Nil => throw new IllegalArgumentException()
case i1 :: tail => {
(tail,env)
}
}
}
}
test("stack machine test 3") {
val lst1 = List(PushI(3.5),PushI(2.5),PushI(4.5),PushI(5.2),AddI,LoadI("x"),LoadI("y"),LoadI("z"),StoreI("y"),LoadI("w"))
val fenv = StackMachineEmulator.emulateStackMachine(lst1)
assert(fenv contains "x")
assert(fenv contains "y")
assert(fenv contains "z")
assert( math.abs(fenv("x") - 9.7 ) <= 1e-05 )
assert( math.abs(fenv("y") - 2.5 ) <= 1e-05 )
assert( math.abs(fenv("z") - 3.5 ) <= 1e-05 )
}
解决方法
您可以使用.updated
更新地图。或添加一个元组,但是Scala必须知道某物是一个元组(map + a -> b
被视为(map + a) -> b
,因此您必须使用map + (a -> b)
)。
您可以使用.get
,。getOrElse
或.apply
从地图中提取值。它们将:返回Option
,缺少则返回值或默认值,如果缺少则提取值或抛出。所以最后一种需要检查。
如果您还记得模式可以通过模式匹配来组合,则可以将解释器编写为:
def emulateSingleInstruction(stack: List[Double],env: Map[String,Double],ins: StackMachineInstruction): (List[Double],Map[String,Double]) =
(ins,stack) match {
case (AddI,i1 :: i2 :: tail) => ((i1 + i2) :: tail) -> env
case (PushI(f),_) => (f :: stack) -> env
case (LoadI(s),i1 :: tail) => tail -> env.updated(s,i1)
case (StoreI(s),_) if env.contains(s) => (env(s) :: stack) -> env
case (PopI,_ :: tail) => tail -> env
case _ => throw new IllegalArgumentException()
}