Last active
August 29, 2015 14:18
-
-
Save aakashns/a69d8e602c3093356b7c to your computer and use it in GitHub Desktop.
Recap of type class from BP1
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
| import annotation.implicitNotFound | |
| @implicitNotFound("No member of type class Group found for type ${T}") | |
| 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 { | |
| def apply[T: Group]: Group[T] = implicitly[Group[T]] | |
| // Instances of Group for Int, Double etc. | |
| } |
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 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 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 | |
| } | |
| 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[T], elems2: Seq[T]): T = | |
| 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