Created
April 23, 2010 16:38
-
-
Save retronym/376773 to your computer and use it in GitHub Desktop.
Hand Rolled Pattern Matcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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