Scala 机器模拟器

Scala Machine Emulator

我正在构建一个堆栈机器模拟器,但我无法弄清楚如何在加载和存储情况下更新 environment/map。我的目标是弄清楚如何更新地图并迭代以获取用于更新地图的正确值。

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 从地图中提取值。他们将:return Option、returns 值或缺失时的默认值,或提取值或在缺失时抛出。所以最后一种需要检查。

如果您还记得模式可以在模式匹配中组合,您可以将解释器编写为:

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()
  }