scala - Scala 机器模拟器
问题描述
我正在构建一个堆栈机器模拟器,但我无法弄清楚如何在加载和存储情况下更新环境/地图。我的目标是弄清楚如何更新地图并迭代以获得用于更新地图的正确值。
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
,在丢失时返回值或默认值,或者在丢失时提取值或抛出。所以最后一种需要检查。
如果您还记得模式可以在模式匹配中组合,您可以将解释器编写为:
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()
}
推荐阅读
- google-bigquery - 使用“Not In”子句时,BigQuery 查询无效地返回“No Results”
- python - 使用散景python将鼠标悬停在一个点上时获取其他列的列表作为注释
- angular - 如何将多个 API 调用从一组值组合成一个 Observable 数组?
- winforms - 如何在 Winforms 中合并 DataGridView 列
- python - Djnago 中的 SwingTime
- corda - 在 Intellij 上运行 Corda-Sample 时发生“NotSerializableException”
- python - 从python中的df列中删除特殊字符和字符串
- ios - 如何在特定视图中修复 PageViewController
- javascript - 如何使用moment js查找一个季度剩余的天数
- excel - 绘制具有多个数据系列的图表