Skip to content

Instantly share code, notes, and snippets.

@NightRa
Last active December 23, 2015 12:29
Show Gist options
  • Save NightRa/6636028 to your computer and use it in GitHub Desktop.
Save NightRa/6636028 to your computer and use it in GitHub Desktop.
Modular pattern matches turned into an extractor.
object Operator {
type op = PartialFunction[Char, (Int, Int) => Int]
val plus: op = {
case '+' => _ + _
}
val minus: op = {
case '-' => _ - _
}
val multi: op = {
case '*' => _ * _
}
val div: op = {
case '/' => _ / _
}
val operators: List[op] = List(plus, minus, multi, div)
val operatorPartialFunction = operators.reduce((f1, f2) => f1 orElse f2)
def unapply(c: Char) = operatorPartialFunction.lift.apply(c)
}
object Test extends App {
'+' match {
case Operator(f) => println(f(2, 3)) // prints 5
case _ =>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment