I new to Scala. As an exercise I am trying to write a match statement over a list of tuples with guards. I am aware that a map would solve the problem but I am trying to gain understanding into pattern matching.
I seek to write a function that takes a List[(Char, Int)]
as argument. The function sorts the entries and if two entries have the same key value they are added together. So the following argument List(('q', 1'), ('a', 1), ('c', 2), ('a', 2), ('c', 1))
would become List(('a', 3), ('c', 3'), ('q', 1))
.
I come with the following code:
def sortAndAggregateList(chars: List[(Char, Int)]) : List[(Char, Int)] = {
chars match {
case (charP1, numP1) :: (charP2, numP2) :: (x : List[(String, Int)]) if (charP1 > charP2) =>
sortAndAggregateList((charP2, numP2) :: (charP1, numP1) :: x)
case (charP1, numP1) :: (charP2, numP2) :: (x : List[(String, Int)]) if (charP1 < charP2) =>
sortAndAggregateList((charP1, numP1) :: (charP2, numP2) :: x)
case (charP1, numP1) :: (charP2, numP2) :: (x : List[(String, Int)]) if (charP1 == charP2) =>
sortAndAggregateList((charP1, numP1 + numP2) :: x)
case Nil =>
Nil
}
}
But I get the following warning:
:14: warning: fruitless type test: a value of type List[(Char, Int)] cannot also be a List[(String, Int)] (the underlying of List[(String, Int)]) (but still might match its erasure)
I tried dropping the List but if I do that I get an error that x
is of type Any
.
Any suggestions?
chars
which is aList[(Char,Int)]
but in the pattern you expectx
to be aList[(String, Int)]
. – Josef