scala - 从 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)
}
推荐阅读
- python - 在组合框中获取所有用户选择的值
- java - entityManager.find 对数据库产生了多少次命中?
- sql - PL/SQL 块以显示表详细信息
- javascript - 如何使用 Javascript 实时从 Firebase-Database 获取数据
- c - 如何将 Gstreamer RTSP 连接到 iPhone?
- python - 如何在 QTableWidget 中有垂直网格线?
- html - 如何在标签块 libxml2 中获取文本?
- ansible - Ansible playbook 输出角色变量和有关您的操作系统的信息
- configuration - 是否可以将 Jackson ObjectMapper 配置为始终使用 @JsonIdentityInfo
- windows - 为什么我的 USB 设备有时会在 windows (7&10) 注册表中创建另一个条目?