Last active
August 29, 2015 14:17
-
-
Save aakashns/fee27ed7ff3ff0c84d46 to your computer and use it in GitHub Desktop.
Group type class with apply method.
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
| object Group { | |
| def apply[T: Group]: Group[T] = implicitly[Group[T]] | |
| // Instances of Group[T]... | |
| } |
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)] = | |
| 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)) | |
| } | |
| } |
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(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