Pattern matching a list with head :: tail (what pattern is used)?

Viewed 173

In the Scala spec there are 14 definitions of "named" patterns (excluding the "pattern binders"), I can't figure out which is the right category of pattern for the following:

Example 1

List("A", "B", "C") match {
   case head :: Nil     => ???
   case "A" :: _ :: Nil => ??? 
   case head :: tail    => ??? 
}

This is purely academic as I'd like to be able to refer to the named pattern in the specification. So the question is kind of about how to interpret the spec and how to be accurate when referring to these kinds of patterns against lists.

For example 1, is it "11. Infix Operation pattern" as :: (aka Cons) is being used infix? or "7. Constructor Pattern" as :: is a constructor? or if we complicate it by using literals in specific positions of the list (L3), does that invoke "4. Literal Patterns"?

Perhaps a simpler case?

Example 2

List(1, 4, 2, 5) match {
   case Nil          => ???
   case head :: tail => ???
}

What would we name that in terms of patterns used?

2 Answers

It is the infix operation pattern (8.1.11) acting as a shorthand for the constructor pattern (8.1.7).

With the constructor pattern alone, example 2 would look like this:

List(1, 4, 2, 5) match {
  case Nil          => ???
  case ::(head, tail) => ???
}

Patterns can be combined so oftentimes we cannot speak of a single kind of pattern taking place. For example

case "A" :: _ :: Nil =>

combines at least four different kinds of pattern

  • constructor pattern because :: is a case class
  • literal pattern because "A" is a string literal
  • stable identifier pattern because Nil is a case object
  • variable pattern because _ is a wild-card
Related