Pattern matching lists of certain size or greater/less

list, pattern-matching, scala

Solution

Yes, although you'll need to reverse the order of the cases:

list match {
  case l @ (_ :: _ :: _ :: _) => other(l)
  case l => op(l)
}

Note that I've bound a new variable `l` to the list in the pattern instead of referring to `list`, and that I've used `_` when I don't need a variable. I'd suggest sticking to both of these practices, but the answer would work exactly the same without them.

Problem

Is there a way to specify a pattern that matches a List with a size greater (or less) or equal a certain value in Scala? For example, if I want to apply the same action to all lists of size 3 or less: ``` list match { case Nil => op(list) case x :: Nil => op(list) case x :: y :: Nil => op(list) case x :: y :: z :: Nil => op(list) case x :: tail => other(list) } ``` Is there a way to reduce this to two cases?

Original source