Skip to content

Instantly share code, notes, and snippets.

@fomkin
Last active January 23, 2017 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fomkin/1af45467518fe9ccd45a1e359ef34732 to your computer and use it in GitHub Desktop.
Save fomkin/1af45467518fe9ccd45a1e359ef34732 to your computer and use it in GitHub Desktop.
def evenlyDivisibleBy(divider: Int): Int ^^ Int = Extractor {
case n if n % divider == 0 => n
}
val evenlyDivisibleByFive = evenlyDivisibleBy(5)
val evenlyDivisibleByThree = evenlyDivisibleBy(3)
val evenlyDivisibleByFifteen = evenlyDivisibleBy(15)
def fizzbuzz(x: Int) = x match {
case evenlyDivisibleByFifteen(_) => "fizzbuzz"
case evenlyDivisibleByFive(_) => "buzz"
case evenlyDivisibleByThree(_) => "fizz"
case _ => x
}
(1 until 100).map(fizzbuzz).foreach(println)
class Extractor[A, R](val f: PartialFunction[A, R]) {
def unapply(x: A): Option[R] = f.lift(x)
def |(other: Extractor[A, R]): Extractor[A, R] = new Extractor(f.orElse(other.f))
}
type ^^[A, R] = Extractor[A, R]
object Extractor {
def apply[A, R](f: PartialFunction[A, R]) =
new Extractor[A, R](f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment