stian stian - 2 months ago 9
Scala Question

How to pattern match on List('(', List[Char],')')?

I am struggling a bit with some pattern matching on a List[Char]. I would like to extract sub-lists that are enclosed by parentheses. So, I would like to extract "test" as a List[Char] when given "(test)". So basically a match on List('(', List[Char],')'). I am able to match on List('(',t,')') where t is a single character, but not a variable amount of characters.

How should this be declared?

val s = "(test)"
s match {
case List('(',t,')') => {
println("matches single character")
}
case '('::x::y => {
//x will be the first character in the List[Char] (after the '(') and y the tail
}
}

Answer
s match {
  case '(' +: t :+ ')' => ...
}

Read about custom extractors in Scala and then see http://www.scala-lang.org/api/2.11.8/index.html#scala.collection.$colon$plus$ to understand how it works.

Note that it'll match any suitable Seq[Char], but a string isn't really one; it can only be converted (implicitly or explicitly). So you can use one of

val s: Seq[Char] = ...some String or List[Char]
val s = someString.toSeq

I expect that performance for String should be good enough (and if it's critical, don't use this); but for large List[Char] this will be quite slow.