Created
August 20, 2012 20:23
-
-
Save philwills/3407522 to your computer and use it in GitHub Desktop.
Pointless re-implementation of match
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
// I wanted to push my knowledge of PartialFunctions, | |
// so this seemed fun in a twisted way | |
// It doesn't do static exhaustiveness checking and is | |
// probably hideously inefficient, but it was lots of fun | |
class Matchable[A](item: A) { | |
def poorMansMatch[B](pfs: PartialFunction[A,B]*) = { | |
val composition = pfs.reduceLeft(_ orElse _) | |
if (composition.isDefinedAt(item)) composition(item) | |
else throw new MatchError(item) | |
} | |
} | |
implicit def any2Matchable[T](x: T) = new Matchable(x) | |
Seq(3,42, "sausages") map (_ poorMansMatch { | |
case 3 => "is the magic number" | |
case 42 => "is also pretty awesome" | |
case _ => "meh" | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment