堆栈机模拟器Scala

问题描述

这里我有一个最终函数,该函数应在指令列表上执行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[Double],Map[String,Double]),SMI:StackMachineInstruction) => {

我不确定是否正确初始化了累加器

def emulateStackMachine(instructionList: List[StackMachineInstruction]): Map[String,Double] =
        {
            instructionList.foldLeft((Nil : List[Double],Double]))((acc:(List[Double],SMI:StackMachineInstruction) => {
                emulateSingleInstruction(acc._1,acc._2,SMI)
            })
        }

解决方法

您不是在创建元组,而是像在两个参数调用中那样传递值。使用以下任一方法:

((Nil : List[Double],Map.empty[String,Double])) // double parens

(List.empty[Double] -> Map.empty[String,Double]) // -> syntax

创建一个元组并将其传递给调用。

此外,您还必须更改输出类型-它是

Map[String,Double]

该函数返回的值是:

(List[Double],Map[String,Double])
def emulateStackMachine(instructionList: List[StackMachineInstruction]): (List[Double],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,SMI)
  })._2
}