缺少参数类型 scala
missing parameter type scala
我在 scala 中输入了以下内容:
def count(e: Int, list: List[Int]): Int =
list.foldLeft(e)((sum) => list match {
case x::xs if e == x => sum = sum + 1
case Nil => sum
})
为什么我在第二行出现错误 "missing parameter type"?
试试这个:
val r = List(1,2,3,4,3,3,3,3,3,3,4,4,5)
def newCount(e: Int, list: List[Int]) = {
list.foldLeft(0)((sum: Int, b: Int) =>{
if(b==e)
sum+1
else sum
}
)
}
println(newCount(3, r)) // 7
所以您的代码存在问题是您使用 foldLeft 的方式没有提供匿名函数的第二个参数。因此,您定义的函数缺少类型参数。
在你的代码中,你试图使用 sum 作为累加器,所以你不需要写 sum = sum + 1
你可以只写 sum + 1
但最重要的是你没有使用 fold left in right方法。
foldLeft 的签名来自文档 here
def foldLeft[B](z: B)(op: (B, A) => B): B
where z is the initial value and a function op which operates on (类型B的累加器,类型A的变量)和return B.
我在 scala 中输入了以下内容:
def count(e: Int, list: List[Int]): Int =
list.foldLeft(e)((sum) => list match {
case x::xs if e == x => sum = sum + 1
case Nil => sum
})
为什么我在第二行出现错误 "missing parameter type"?
试试这个:
val r = List(1,2,3,4,3,3,3,3,3,3,4,4,5)
def newCount(e: Int, list: List[Int]) = {
list.foldLeft(0)((sum: Int, b: Int) =>{
if(b==e)
sum+1
else sum
}
)
}
println(newCount(3, r)) // 7
所以您的代码存在问题是您使用 foldLeft 的方式没有提供匿名函数的第二个参数。因此,您定义的函数缺少类型参数。
在你的代码中,你试图使用 sum 作为累加器,所以你不需要写 sum = sum + 1
你可以只写 sum + 1
但最重要的是你没有使用 fold left in right方法。
foldLeft 的签名来自文档 here
def foldLeft[B](z: B)(op: (B, A) => B): B
where z is the initial value and a function op which operates on (类型B的累加器,类型A的变量)和return B.