从Doubles列表返回List [Double],Map [String,Double]

问题描述

我正在尝试返回列表和地图的元组。我已经获得了可以正确编译的列表,但是我不确定如何使用映射和列表来获取与列表中的键和值匹配的映射。这是我到目前为止的内容

我已经能够实现返回列表。但是我需要返回(List [Double],Map [String,Double])

    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()
        }
        //USE V1 and V2
        case SubI => stack match{
            case i1 :: i2 :: tail => (i1 - i2 :: tail,env)
            case _ => throw new IllegalArgumentException()

        }
        case MultI => stack match{
            case i1 :: i2 :: tail => (i1 * i2 :: tail,env)
            case _ => throw new IllegalArgumentException()
        }
        //USE V1 and V2
        case DivI => stack match{
            case i1 :: i2 :: tail => (i1 / i2 :: tail,env)
            case _ => throw new IllegalArgumentException()
        }
        case ExpI => stack match{
            case Nil => throw new IllegalArgumentException()
            case head :: tail => {
                (scala.math.exp(head) :: tail,env)
            }
        }
        case LogI => stack match{
            case Nil => throw new IllegalArgumentException()
            case head :: tail => {
                if (head > 0){(scala.math.log(head) :: tail,env)}
                else{ throw new IllegalArgumentException()}
            }
        }
        case SinI => stack match{
            case Nil => throw new IllegalArgumentException()
            case head :: tail => {
                (scala.math.sin(head) :: tail,env)
            }
        }
        case CosI => stack match{
            case Nil => throw new IllegalArgumentException()
            case head :: tail => {
                (scala.math.cos(head) :: tail,env)
            }
        }
        case PushI(f) => (f :: stack,env)

        case PopI => stack match{
            case Nil => throw new IllegalArgumentException()
            case i1 :: tail => {
                (tail,env)
            }
        }
    }
}

解决方法

由于您的示例操作似乎并没有修改环境,而是仅修改了堆栈,因此我了解您只是在问如何在返回值中组合新堆栈和环境。

def emulateSingleInstruction(stack: List[Double],env: Map[String,Double],ins: StackMachineInstruction): (List[Double],Map[String,Double]) = {
    val newStack = ins match {
        case AddI => // your code. Looks good...
    }
    val newEnv = // expression that evaluates to the updated environment
    (newStack,newEnv)
}