简体   繁体   中英

missing parameter type scala

I typed the following in 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. Hence you are getting the type parameter missing for your the function you have defined.

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.

the signature for foldLeft is from the documentation here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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