views:

697

answers:

2

Scala has a language feature to support disjunctions in pattern matching ('Pattern Alternatives').

x match {
    case _: String | _: Int => 
    case _ =>
}

However, I often need to trigger an action if the scrutinee satisfies PatternA and PatternB (conjunction.)

I created a pattern combinator '&&' that adds this capability. Three little lines that really remind me why I love Scala!

// Splitter to apply two pattern matches on the same scrutinee.
case object && {
  def unapply[A](a: A) = Some((a, a))
}

// Extractor object matching first character.
object StartsWith {
  def unapply(s: String) = s.headOption
}

// Extractor object matching last character.
object EndsWith {
  def unapply(s: String) = s.reverse.headOption
}

// Extractor object matching length.
object Length {
  def unapply(s: String) = Some(s.length)
}

"foo" match {
  case StartsWith('f') && EndsWith('f') => "f.*f"
  case StartsWith('f') && EndsWith(e) && Length(3) if "aeiou".contains(e) => "f..[aeiou]"
  case _ => "_"
}

Points for Discussion

  1. Is there an existing way to do this?
  2. Are there problems with this approach?
  3. Are there other useful combinators that could be created with this approach? (e.g Not)
  4. Should such a combinator be added to the standard library?

UPDATE I've just been asked how the compiler interprets case A && B && C. These are Infix Operator Patterns (Section 8.1.9 of the Scala Reference). You could also express this with normal Extract Patterns (8.1.7) as &&(&&(A, B), C). Notice how the expressions are associated left to right, as per normal infix operator method calls like Boolean#&& in val b = true && false && true.

+8  A: 

I really like this trick. I do not know of any existing way to do this, and I don't foresee any problem with it -- which doesn't mean much, though. I can't think of any way to create a Not.

As for adding it to the standard library... perhaps. But I think it's a bit hard. On the other hand, how about talking Scalaz people into including it? It looks much more like their own bailiwick.

Daniel
I can't see a way to build `Not` either :(I could add this to Scalaz, its just the audience is a bit smaller and it actually doesn't fit all that nicely. Pattern matching like this isn't particularly compositional, the preferred approach would be combining checks and extractors through the Validation Applicative Functor or Monad.
retronym
+4  A: 

A possible problem with this is the bloated translation that the pattern matcher generates. Here is the translation of the sample program, generated with scalac -print. Even -optimise fails to simplify the if (true) "_" else throw new MatchError() expressions.

Large pattern matches already generate more bytecode than is legal for a single method, and use of this combinator may amplify that problem.

If && was built into the language, perhaps the translation could be smarter. Alternatively, small improvements to -optimise could help.

retronym