Last active
August 29, 2015 14:17
-
-
Save aakashns/02fdca3a8fadafccb9e5 to your computer and use it in GitHub Desktop.
Group type class with context bounds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| implicit def pairGroup[T1: Group, T2: Group]: Group[(T1, T2)] = { | |
| val t1Group = implicitly[Group[T1]] | |
| val t2Group = implicitly[Group[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)) | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| implicit def pairGroup[T1: Group, T2: Group]: Group[(T1, T2)] = ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def sum[T: Group](elems: Seq[T]): T = | |
| elems.foldLeft(implicitly[Group[T]].zero)(implicitly[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[T], elems2: Seq[T]): T = | |
| implicitly[Group[T]].minus(sum(elems1), sum(elems2)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def sum[T: Group](elems: Seq[T]): T = ... | |
| def sumNonEmpty[T: Group](elems: Seq[T]): Option[T] = ... | |
| def sumDifference[T: Group](elems1: Seq[Int], elems2: Seq[Int]): Int = ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment