缺少参数类型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
   })

为什么第二行“缺少参数类型”出现错误?

pengsijing 回答:缺少参数类型scala

尝试一下:

 val r = List(1,2,3,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,但最重要的是,您并没有以正确的方式使用左折。

foldLeft的签名来自文档here

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

其中z是初始值,函数op对其进行操作(类型B的累加器,类型A的变量)并返回B。

本文链接:https://www.f2er.com/2393321.html

大家都在问