Skip to content

Instantly share code, notes, and snippets.

@vsuharnikov
Created April 4, 2016 13:50
Show Gist options
  • Save vsuharnikov/1c391355883652738e42402e471fb8d6 to your computer and use it in GitHub Desktop.
Save vsuharnikov/1c391355883652738e42402e471fb8d6 to your computer and use it in GitHub Desktop.
trait BinaryOperation[T] {
def apply(a: T, b: T): T
}
trait AssociativeBinaryOperation[T] extends BinaryOperation[T]
trait Reduce[F[_]] {
def apply[T](xs: F[T])(op: BinaryOperation[T]): T
}
val sum = new AssociativeBinaryOperation[Int] {
override def apply(a: Int, b: Int): Int = a + b
}
val div = new BinaryOperation[Int] {
override def apply(a: Int, b: Int): Int = a / b
}
val reduce = new Reduce[Seq] {
override def apply[T](xs: Seq[T])(op: BinaryOperation[T]): T = op match {
case _: AssociativeBinaryOperation[_] ⇒ println("associative"); xs reduce op.apply
case _ ⇒ println("non-associative"); xs reduceLeft op.apply
}
}
val xs = Seq(100, 4, 5)
reduce(xs)(sum)
// associative
// res0: Int = 109
reduce(xs)(div)
// non-associative
// res1: Int = 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment