首页 > 解决方案 > 从 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)
            }
        }
    }
}

标签: scalapattern-matchingemulation

解决方案


由于您的示例操作似乎没有修改环境,而只是修改了堆栈,所以我理解您只是在询问如何在返回值中结合新堆栈和环境。

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

推荐阅读