[英]Type mismatch scala in Fold method
I am learning Scala and I'm having some troubles to write a simple reducer function. 我正在学习Scala,并且在编写一个简单的reducer函数时遇到了一些麻烦。 I want to count how many times a value appear in a list. 我想计算一个值出现在列表中的次数。 Thus, I wrote a reducer/folding function which takes an immutable map as initial value, and then iterates the list "updating" the map with the number of times a value appears in the list. 因此,我编写了一个reducer / folding函数,该函数将不可变的映射作为初始值,然后用值在列表中出现的次数迭代列表,以“更新”该映射。 Quite simple stuff, but I am having an issue with the type system (Ahhh... too much time spent on JavaScript and Python) 很简单的东西,但是我在类型系统上遇到了问题(啊...在JavaScript和Python上花了太多时间)
This is the function: 这是功能:
def times(chars: List[Char]): List[(Char, Int)] = {
val acc:Map[Char, Int] = Map()
def count(acc:Map[Char, Int], c:Char) = {
if (acc contains c) acc + (c -> (acc(c) + 1))
else acc + (c -> 1)
}
chars.fold(acc)(count).toList
}
I can't understand why I am getting the following type error : 我不明白为什么会收到以下类型错误:
[error] /Users/giuseppe/courses/scala_functional_programing/lessons/week_4/assignment/src/main/scala/patmat/Huffman.scala:85: type mismatch;
[error] found : (Map[Char,Int], Char) => scala.collection.immutable.Map[Char,Int]
[error] required: (Any, Any) => Any
[error] chars.fold(acc)(count)
[error] ^
[error] /Users/giuseppe/courses/scala_functional_programing/lessons/week_4/assignment/src/main/scala/patmat/Huffman.scala:85: type mismatch;
[error] found : Any
[error] required: List[(Char, Int)]
[error] chars.fold(acc)(count)
[error] ^
[error] two errors found
Is Map[Char, Int]
a subtype of Any
? Map[Char, Int]
是Any
的子类型吗?
* EDIT * *编辑*
Even more interesting, I've just discovered that if I use foldLeft
, it works properly. 更有趣的是,我刚刚发现,如果我使用foldLeft
,它可以正常工作。 :confused: Why?? :confused:为什么?
Any help would be really appreciated. 任何帮助将非常感激。 Thank you 谢谢
It's looks like you need foldLeft function instead of fold. 看起来您需要foldLeft函数而不是fold。 It has proper signature. 它具有适当的签名。
def foldLeft[B](z: B)(f: (B, A) => B): B = { // in your case B is Map and A is Char
def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1 = foldLeft(z)(op) // in your case arguments of count functions should be same
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.