Fricken Hamster
Fricken Hamster

Reputation: 569

scala append to to list of tuples in foldLeft?

I'm a beginner in scala, and I'm wondering how to append, or create a new list of tuples with a tuple at the head of another tuple.

Right now I am doing

list.foldLeft(List[(String, Int)]())((ll:List[(String, Int)], str:String) => 
if (str == ll.head._1) (str, ll.head._2 + 1) :: ll.tail.head
else (str, 1) :: ll.head)

However the error I get is that there is no :: operator for tuples.

Upvotes: 0

Views: 3822

Answers (1)

Hugh
Hugh

Reputation: 8932

If I understand what you're trying to do, the reason for this is that you're trying to use the first element of the tail of the list rather than the tail itself as the right-hand argument to ::.

You should be able to use something like:

list.foldLeft(List[(String, Int)]())((ll, str) =>
  if (str == ll.head._1) (str, ll.head._2 + 1) :: ll.tail
  else (str, 1) :: ll)

However you'll then hit an error from trying to take the head of an empty list. So a full working version would be like

list.foldLeft(List[(String, Int)]()) {
  case ((hs, hc) :: tail, str) if hs == str ⇒ (str, hc + 1) :: tail
  case (ll, str) ⇒ (str, 1) :: ll
}

Upvotes: 1

Related Questions