1

I have the following helper function. I am trying to create a word frequency List. (a,b,a) => [(a,2),(b,1)]:

def add_to_lop(c:Char, lop: List[(Char, Int)]):List[(Char, Int)] = {
      lop match {
        case List() => List((c,1))
        case (c, _)::xs => add_to_pair(c,lop.head)::lop.tail
        case _ => lop.head::add_to_lop(c, lop.tail)
      }

I think so long as the head of lop does not satisfy lop.head._1==c, the case should reach the third one (barring lop being empty where it is the first case). However compilation warns that the third case is almost unreachabe - case _ => lop.head::add_to_lop(c, lop.tail); Unreachable case except for null (if this is intentional, consider writing case null => instead).. Can you help me identify my mistake?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
figs_and_nuts
  • 4,870
  • 2
  • 31
  • 56

1 Answers1

3

Write

case (`c`, _)::xs =>

with backticks instead of

case (c, _)::xs =>

In the pattern, c without backtics is a new variable, so matches everything, not only the previous c.

scala Does match end in Nil?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • OP should have got a warning about this like "shadowing variable", isn't it? I'm pretty sure I had such warnings but I don't remember with which compilation flag. – Gaël J Mar 10 '23 at 06:53
  • @GaëlJ Not sure https://docs.scala-lang.org/overviews/compiler-options/index.html https://docs.scala-lang.org/scala3/guides/migration/options-lookup.html – Dmytro Mitin Mar 10 '23 at 12:39