Tuesday, February 16, 2010

And Case Statements

Recently I encountered a good question on Stack Overflow about matching.
http://stackoverflow.com/questions/2261358/pattern-matching-with-conjunctions-patterna-and-patternb.

As mentioned in an earlier post Matching with Or case expressions suppose 'or' expression combination using the '|' character. However 'and' combinations are not possible.

One solution is to build an && extractor object as follows:
  1. scala> case object && {  def unapply[A](a: A) = Some((a, a))}
  2. defined module $amp$amp
  3. scala> object StartsWith {  def unapply(s: String) = s.headOption}
  4. defined module StartsWith
  5. scala> object EndsWith {  def unapply(s: String) = s.reverse.headOption}
  6. defined module EndsWith
  7. scala> "foo" match {  case StartsWith('f') && EndsWith('o') => println("f*o") }
  8. f*o

Note: this is a scala 2.7 solution Scala 2.8 can be used to improve the EndsWith extractor by using the method lastOption instead of s.reverse.headOption.

No comments:

Post a Comment