Skip to content

Instantly share code, notes, and snippets.

@retronym
Created April 23, 2010 16:38
Show Gist options
  • Save retronym/376773 to your computer and use it in GitHub Desktop.
Save retronym/376773 to your computer and use it in GitHub Desktop.
Hand Rolled Pattern Matcher
object Match {
trait Matchable[A] {
def `match`[B](cases: PartialFunction[A, B]*): B
}
implicit def anyToMatchable[A](a: A): Matchable[A] = new Matchable[A]{
def `match`[B](cases: PartialFunction[A, B]*) = {
cases.toList match {
case Nil => throw new MatchError(a)
case x :: _ if x.isDefinedAt(a) => x(a)
case _ :: xs => a `match` (xs : _*)
}
}
}
}
import Match._
import Stream._
(Stream(1), Stream(2)) `match` (
{case (Stream.Empty, Stream.Empty) => None},
{case (l #:: ls, rs) => None}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment