Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stable identifier required during pattern matching? (Scala)

Trying to produce a list of tuples showing prime factor multiplicity... the idea is to match each integer in a sorted list against the first value in a tuple, using the second value to count. Could probably do it more easily with takeWhile, but meh. Unfortunately my solution won't compile:

  def primeFactorMultiplicity (primeFactors: List[Int]) = {

    primeFactors.foldRight (List[(Int, Int)]()) ((a, b) => (a, b) match {
      case (_, Nil)       => (a, 1) :: b
      case (b.head._1, _) => (a, b.head._2 + 1) :: b.tail
      case _              => (a, 1) :: b
    })
  }

It says "error: stable identifier required, but b.head._1 found." But changing the second case line to the following works fine:

      case (i, _) if (i == b.head._1) => (a, b.head._2 + 1) :: b.tail

Why is this, and why can't the compiler cope if there is such a simple fix?

like image 841
Luigi Plinge Avatar asked Jun 26 '11 13:06

Luigi Plinge


People also ask

What is stable identifier?

A stable identifier for a UI control is an identifier that does not change between invocations of the control and between different versions of the application, in which the UI control exists.

How does Scala pattern matching work?

Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.


1 Answers

A variable in a pattern captures the value in that position; it does not do a comparison. If the syntax worked at all, the result would be to put the value of a into b.head._1, overwriting the current value. The purpose of this is to let you use a pattern to pull something out of a complex structure.

like image 171
geekosaur Avatar answered Oct 21 '22 06:10

geekosaur