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/fee27ed7ff3ff0c84d46 to your computer and use it in GitHub Desktop.

Select an option

Save aakashns/fee27ed7ff3ff0c84d46 to your computer and use it in GitHub Desktop.
Group type class with apply method.
object Group {
def apply[T: Group]: Group[T] = implicitly[Group[T]]
// Instances of Group[T]...
}
implicit def pairGroup[T1: Group, T2: Group]: Group[(T1, T2)] =
new Group[(T1, T2)] {
val zero = (Group[T1].zero, Group[T2].zero)
def plus(x: (T1, T2), y: (T1, T2)): (T1, T2) = (x, y) match {
case ((x1, x2), (y1, y2)) =>
(Group[T1].plus(x1, y1), Group[T2].plus(x2, y2))
}
def inverse(x: (T1, T2)) = x match {
case (x1, x2) => (Group[T1].inverse(x1), Group[T2].inverse(x2))
}
}
def sum[T: Group](elems: Seq[T]): T =
elems.foldLeft(Group[T].zero)(Group[T].plus)
def sumNonEmpty[T: Group](elems: Seq[T]): Option[T] =
if (elems.isEmpty) None
else Some(sum(elems))
def sumDifference[T: Group](elems1: Seq[Int], elems2: Seq[Int]): Int =
Group[T].minus(sum(elems1), sum(elems2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment