Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

head :: tail pattern matching for strings

Can I do something like this with a string:

s match {
  case "" => ...
  case head +: tail => ...
}

where head is the first character and tail is the remaining string?

In the above code the type of head is Any, and I would like it to be String or Char.

like image 242
Ilya Kogan Avatar asked Nov 25 '14 07:11

Ilya Kogan


1 Answers

case h +: t means case +:(h, t). There is object +: with unapply method.

Method unapply of object +: is defined only for SeqLike and String is not SeqLike.

You need a custom unapply method like this:

object s_+: {
  def unapply(s: String): Option[(Char, String)] = s.headOption.map{ (_, s.tail) }
}

"abc" match {
  case h s_+: t => Some((h, t))
  case _ => None
}
// Option[(Char, String)] = Some((a,bc))
like image 181
senia Avatar answered Oct 05 '22 05:10

senia