0
votes

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"?

1
Good job with code highlighting! Please post your compiler output more completely, like error: wrong number of parameters; expected = 2 and the rest of it. Often it lets people understand the problem better. Also specify where you put this code - was it Scala REPL ( interactive command line evaluation ) or was it a scala file which you compiled?Utgarda
Thank you! It was Scala REPLuser13370875

1 Answers

2
votes

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.