Skip to content

Instantly share code, notes, and snippets.

@philwills
Created August 20, 2012 20:23
Show Gist options
  • Save philwills/3407522 to your computer and use it in GitHub Desktop.
Save philwills/3407522 to your computer and use it in GitHub Desktop.
Pointless re-implementation of match
// 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