简体   繁体   English

缺少参数类型 scala

[英]missing parameter type scala

I typed the following in 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
   })

Why am I getting an error on the second Line "missing parameter type"?为什么我在第二行“缺少参数类型”上出现错误?

Try this:尝试这个:

 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

so problem with your code is the way you are using foldLeft you are not providing the second parameter of your anonymous function.所以你的代码的问题是你使用 foldLeft 的方式你没有提供匿名 function 的第二个参数。 Hence you are getting the type parameter missing for your the function you have defined.因此,您将获得您定义的 function 缺少的类型参数。

In your code you are trying to use sum as accumulator so you don't need to write sum = sum + 1 you can just write sum + 1 but most important you are not using fold left in the right way.在您的代码中,您尝试使用 sum 作为累加器,因此您不需要编写sum = sum + 1您可以只编写sum + 1但最重要的是您没有以正确的方式使用左折叠。

the signature for foldLeft is from the documentation here foldLeft 的签名来自此处的文档

def foldLeft[B](z: B)(op: (B, A) => B): B

where z is the initial value and a function op which operates on (accumulator of type B, A variable of type A) and return B.其中 z 是初始值和一个 function 运算,它在(B 类型的累加器,A 类型的变量)上运行并返回 B。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM