Martin Lindemann
Martin Lindemann

Reputation: 11

pattern matching in scala / recursion

I'd like to implement a function that counts the number of same characters directly following. This function always and only starts at the head.

function((Char, Int), List[char]) => ((Char, Int), List[Char])

e.g. (('b',0), List('b','b','x','x')) => (('b', 2), List('x', 'x'))

  def function: ((Char, Int), List[Char]) => ((Char, Int), List[Char])={
    case(('a', b), Nil) => (('a',b), Nil)
    case(('a', b), t::xs)  => (('a', b), t::xs)
    case (('a', b), a::xs) => function(('a', b+1),xs)
  }

I can't find the mistake in my pattern matching.

Are the two characters in the line

case (('**a**', b), **a**::xs) => function(('a', b+1),xs)

the same (like 'a' == 'a'), when I give them the same character?

thanks!

Upvotes: 1

Views: 1683

Answers (2)

Peter Neyens
Peter Neyens

Reputation: 9820

I think this does what you want:

def function: ((Char, Int), List[Char]) => ((Char, Int), List[Char]) = {
  case ((a, b), Nil) => ((a,b), Nil)
  case ((a, b), c::xs) if a == c => function((a, b+1),xs)
  case other  => other
}

Output:

scala> function(('a', 0), "aaaabbbcc".toList)
res0: ((Char, Int), List[Char]) = ((a,4),List(b, b, b, c, c))

Something simpler might be:

def countChar(char: Char, list: List[Char]) : ((Char, Int), List[Char]) = {
  val equalChars = list.takeWhile(_ == char)
  val n = equalChars.length
  ((char, n), list.drop(n))
}

Upvotes: 4

jwvh
jwvh

Reputation: 51271

These two cases do the same thing:

case (('a', b), t::xs) => ...
case (('a', b), a::xs) => ...

They match the 'a' of the tuple, assign the 2nd part of the tuple to b, assign the head of the collection to a variable (t in the 1st case, a in the 2nd) and assign the rest of the collection to xs.

Probably not what you had in mind.

Upvotes: 1

Related Questions