Last active
December 23, 2015 12:29
-
-
Save NightRa/6636028 to your computer and use it in GitHub Desktop.
Modular pattern matches turned into an extractor.
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 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