Skip to content

Instantly share code, notes, and snippets.

@aakashns
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save aakashns/f6c61a5f8af587dde756 to your computer and use it in GitHub Desktop.

Select an option

Save aakashns/f6c61a5f8af587dde756 to your computer and use it in GitHub Desktop.
Group type class with helper class and implicit class for syntax
object GroupSyntax {
implicit class GroupOps[T](val x: T) extends AnyVal {
def |+|(y: T)(implicit ev: Group[T]): T = ev.plus(x, y)
def inverse(implicit ev: Group[T]): T = ev.inverse(x)
def |-|(y: T)(implicit ev: Group[T]): T = ev.minus(x, y)
}
def zero[T: Group]: T = Group[T].zero
}
object GroupSyntax {
class GroupOps[T](val x: T) extends AnyVal { ... }
implicit def toGroupOps[T](x: T) = new GroupOps(x)
//...
}
object GroupSyntax {
implicit class GroupOps[T: Group](x: T) {
def |+|(y: T): T = Group[T].plus(x, y)
def inverse: T = Group[T].inverse(x)
def |-|(y: T): T = Group[T].minus(x, y)
}
def zero[T: Group]: T = Group[T].zero
}
object GroupSyntax {
class GroupOps[T: Group](x: T) { ... }
implicit def toGroupOps[T: Group](x: T) = new GroupOps(x)
//...
}
import GroupSyntax._
implicit def PairGroup[T1: Group, T2: Group]: Group[(T1, T2)] =
new GroupAux[(T1, T2)](
(zero[T1], zero[T2]),
(x, y) => (x._1 |+| y._1, x._2 |+| y._2),
x => (x._1.inverse, x._2.inverse)
)
def sum[T: Group](elems: Seq[T]): T = elems.foldLeft(zero[T]) { _ |+| _ }
def sumDifference[T: Group](elems1: Seq[T], elems2: Seq[T]): T =
sum(elems1) |-| sum(elems2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment