In scala, how can I use pattern match to match a list with specified length?

functional-programming, list, pattern-matching, scala

Solution

You don't have to match on Nil. What you could do instead is match on the rest.

1::Nil match {
   case 1::ts::rest => "Starts with 1. More than one element"
   case 1::Nil => "Starts with 1. Only one element"
}

With this code rest is than either a List or Nil and you make sure that the element has more than 1 element with the match on ts and then rest

Problem

My codes looks like this: ``` 1::2::Nil match { case 1::ts::Nil => "Starts with 1. More than one element" case 1::Nil => "Starts with 1. Only one element" } ``` I tried to use `1::ts::Nil` to match the List who starts with `1` and whose length is greater than 1. It workes well for 2-element list, however, this pattern doesn't work for `3-element list`, for example: ``` 1::2::3::Nil match { case 1::ts::Nil => "Starts with 1. More than one element" case 1::Nil => "Starts with 1. Only one element" } ``` This won't work..Does anyone have ideas about this?

Original source