scala - Why fold infers Any?
问题描述
I'm compiling with Scala 2.11.12 and this declaration:
import scala.collection.mutable.Stack
def stackToInt(stack: Stack[Int]): Int =
stack.zipWithIndex.fold(0){ case (z: Int, (piece: Int, index: Int)) =>
piece match {
case 1 => (1 << index) + z
case _ => z
}
}
gives:
stack.zipWithIndex.fold(0){ case (z: Int, (piece: Int, index: Int)) =>
^
error: type mismatch;
found : Any
required: Int
I've been dealing with stuff like this many times when writing folds in this project (first one in Scala) and I always found a different way to make it work, but maybe if I understand it I will stop hitting this wall.
解决方案
因为您需要使用foldLeft
而不是折叠:
import scala.collection.mutable.Stack
def stackToInt(stack: Stack[Int]): Int =
stack.zipWithIndex.foldLeft(0) { case (z: Int, (piece: Int, index: Int)) =>
piece match {
case 1 => (1 << index) + z
case _ => z
}
}
斯卡蒂:https ://scastie.scala-lang.org/VzfKqHZ5QJyNPfwpLVGwSw
fold
不起作用,因为它是语义的:fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1
- 因此在你的情况下zipWithIndex
给出(Int, Int)
type 而不是 expected Int
,并且函数内部返回Int
- 所以最后你会看到推断类型- 和Any
之间的共同祖先。(Int, Int)
Int
并且foldLeft[Z](zero: Z)
有推断Int
,因为你给0
推荐阅读
- java - 如何将拦截器添加到 WebSocket
- laravel - 如何使用 php 在谷歌云上提取 zip 文件
- python - Python'str'对象即使在列表上操作时也没有属性'append'?
- ide - Atmel Studio 输出文件--.aoi
- javascript - 如何在不使用 JavaScript 的情况下为特定类型的所有元素添加属性
- python - 为什么在尝试显示 MySql 数据库时此命令在 Python 中不起作用
- c# - 如何使用 FormData 使用 .Net Core Web API 验证/确保所需文件已上传或不上传?
- firebase - 为什么 Firebase 动态链接先在网络中打开,然后在安装后在应用程序中打开?
- php - 使用 Laravel 为 Singpass 生成客户端断言密钥的问题
- javascript - JSON.parse 本地存储中的未定义对象