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

Select an option

Save aakashns/108da2dfc2b6d772f544 to your computer and use it in GitHub Desktop.
Group type class with no improvements
implicit object DoubleGroup extends Group[Double] {
val zero: Double = 0.0
def plus(x: Double, y: Double): Double = x + y
def inverse(x: Double): Double = -x
}
trait Group[T] {
def zero: T
def plus(x: T, y: T): T
def inverse(x: T): T
def minus(x: T, y: T): T = plus(x, inverse(y))
}
object Group {
// Instances of Group[T] for various types T can be defined here..
}
implicit object IntGroup extends Group[Int] {
val zero: Int = 0
def plus(x: Int, y: Int): Int = x + y
def inverse(x: Int): Int = -x
}
implicit def pairGroup[T1, T2](
implicit t1Group: Group[T1],
t2Group: Group[T2]
): Group[(T1, T2)] = new Group[(T1, T2)] {
val zero = (t1Group.zero, t2Group.zero)
def plus(x: (T1, T2), y: (T1, T2)): (T1, T2) = (x, y) match {
case ((x1, x2), (y1, y2)) =>
(t1Group.plus(x1, y1), t2Group.plus(x2, y2))
}
def inverse(x: (T1, T2)) = x match {
case (x1, x2) => (t1Group.inverse(x1), t2Group.inverse(x2))
}
}
def sum[T](elems: Seq[T])(implicit tGroup: Group[T]): T =
elems.foldLeft(tGroup.zero)(tGroup.plus)
def sumNonEmpty[T](elems: Seq[T])(implicit tGroup: Group[T]): Option[T] =
if (elems.isEmpty) None
else Some(sum(elems))
def sumDifference[T](
elems1: Seq[T],
elems2: Seq[T]
)(
implicit tGroup: Group[T]
): Int = tGroup.minus(sum(elems1), sum(elems2))
sum(Seq(1, 1, 2, 3, 5, 8, 13, 21, 34, 55))
sum(Seq(1.0, 1.0, 1.414, 1.732, 2.236, 2.828, 3.605, 4.582, 5.830, 7.416))
sum(Seq((1, 1), (4, 8), (9, 27), (25, 125), (64, 512)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment