堆栈机模拟器Scala [英] Stack Machine Emulator Scala

查看:206
本文介绍了堆栈机模拟器Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有一个最终函数,该函数应该在指令列表上执行foldLeft。我正在

Here I have a final function which should execute foldLeft on a list of instructions. I'm getting

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) => {

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

I'm not sure if I'm initializing the accumulator correctly

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


推荐答案

您不是在创建元组而是在传递值就像是两个参数调用一样。

You aren't creating a tuple but passing values as if it was two parameter call. Use either:

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

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

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

to create a tuple and pass it into a call.

另外,您必须更改您的输出类型-

Additionally you have to change you output type - it's

Map[String, Double]

而函数返回的值是:

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

这篇关于堆栈机模拟器Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆