Joggi
Joggi

Reputation: 103

How to properly use fold left in a scala function

I've a problem with this part of code in scala

object Test12 {
  def times(chars: List[Char]): List[(Char, Int)] = {
    val sortedChars = chars.sorted
    sortedChars.foldLeft (List[(Char, Int)]()) ((l, e) =>
        if(l.head._1 == e){
            (e, l.head._2 + 1) :: l.tail
        } else {
            (e, 1) :: l
        } )
  }

  val s = List('a', 'b')

  val c = times s
}

The last line give an error :

Missing arguments for method times; follow this method with `_' if you want to treat it as a partially applied function

But I don't see why, because I've given 2 arguments to the last function - foldLeft.

Thanks in advance for help!

The idea of code is to count how much time each character is present in a given list

Upvotes: 0

Views: 822

Answers (2)

BeniBela
BeniBela

Reputation: 16917

The syntax of times is fine, but you need to use parenthesis when calling it, i.e. :

val c = times(s)

But it won't work because you use l.head without checking if l is Nil, and an empty list does not have a head. You can e.g. check with match for that:

def times(chars: List[Char]): List[(Char, Int)] = {
  val sortedChars = chars.sorted
  sortedChars.foldLeft (List[(Char, Int)]()) ((a,b) => (a,b) match {
    case (Nil, e) => (e, 1) :: Nil
    case ((e, count) :: l, f) => 
        if (e == f) (e, count + 1) :: l
        else (f, 1) :: (e, count) :: l
  })
}

Although an easier way is to use the higher level collection functions:

def times(chars: List[Char]) = chars.groupBy(c=>c).map(x=>(x._1,x._2.length)).toList

Upvotes: 3

senia
senia

Reputation: 38045

val c = times s

You can't call method without brackets like this. Try times(s) or this times s.

Upvotes: 1

Related Questions