堆栈计算机仿真器Scala
这里我有一个最终的函数,它应该在指令列表上执行foldLeft。我要走了堆栈计算机仿真器Scala,scala,stack,pattern-matching,emulation,Scala,Stack,Pattern Matching,Emulation,这里我有一个最终的函数,它应该在指令列表上执行foldLeft。我要走了 type mismatch; found : (List[Double], scala.collection.immutable.Map[String,Double]) required: Map[String,Double] instructionList.foldLeft(Nil : List[Double], Map.empty[String,Double])((acc:(List[D
type mismatch;
found : (List[Double], scala.collection.immutable.Map[String,Double])
required: Map[String,Double]
instructionList.foldLeft(Nil : List[Double], Map.empty[String,Double])((acc:(List[Double], Map[String,Double]), SMI:StackMachineInstruction) => {
我不确定是否正确初始化了累加器
def emulateStackMachine(instructionList: List[StackMachineInstruction]): Map[String, Double] =
{
instructionList.foldLeft((Nil : List[Double], Map.empty[String,Double]))((acc:(List[Double], Map[String,Double]), SMI:StackMachineInstruction) => {
emulateSingleInstruction(acc._1, acc._2, SMI)
})
}
您不是在创建元组,而是在传递值,就像它是两个参数调用一样。使用以下任一选项:
((Nil : List[Double], Map.empty[String,Double])) // double parens
或
创建元组并将其传递到调用中
此外,您必须更改输出类型-它是
Map[String, Double]
而函数返回的值为:
(List[Double], Map[String,Double])
这完全有道理。令人惊讶的是,我收到了相同的错误消息,同时更改了输出类型。我看到了您的编辑。编译正确,但现在我发现:Map[String,Double]required:(List[Double],scala.collection.immutable.Map[String,Double])emulateSingleInstruction(acc.\u 1,acc.\u 2,smi)。\u 2当您可用时,是否有针对LoadI和StoreI的单行解决方案?这里是我的位置。
case-class-LoadI(s:String)extends-stackmachine指令
case-class-StoreI(s:String)extends-stackmachine指令case-LoadI=>…
case-StoreI=>代码>@jwvh嘿!谢谢你在另一个问题上的帮助,伙计。与其他解决方案类似,我实际上收到了相同的错误消息
(List[Double], Map[String,Double])
def emulateStackMachine(instructionList: List[StackMachineInstruction]): (List[Double], Map[String, Double]) = {
instructionList.foldLeft(List.empty[Double] -> Map.empty[String,Double])((acc, SMI) => {
emulateSingleInstruction(acc._1, acc._2, SMI)
})
}
// or
def emulateStackMachine(instructionList: List[StackMachineInstruction]): Map[String, Double] = {
instructionList.foldLeft(List.empty[Double] -> Map.empty[String,Double])((acc, SMI) => {
emulateSingleInstruction(acc._1, acc._2, SMI)
})._2
}