Last active
August 29, 2015 14:17
-
-
Save aakashns/f6c61a5f8af587dde756 to your computer and use it in GitHub Desktop.
Group type class with helper class and implicit class for syntax
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 GroupSyntax { | |
| implicit class GroupOps[T](val x: T) extends AnyVal { | |
| def |+|(y: T)(implicit ev: Group[T]): T = ev.plus(x, y) | |
| def inverse(implicit ev: Group[T]): T = ev.inverse(x) | |
| def |-|(y: T)(implicit ev: Group[T]): T = ev.minus(x, y) | |
| } | |
| def zero[T: Group]: T = Group[T].zero | |
| } |
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 GroupSyntax { | |
| class GroupOps[T](val x: T) extends AnyVal { ... } | |
| implicit def toGroupOps[T](x: T) = new GroupOps(x) | |
| //... | |
| } |
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 GroupSyntax { | |
| implicit class GroupOps[T: Group](x: T) { | |
| def |+|(y: T): T = Group[T].plus(x, y) | |
| def inverse: T = Group[T].inverse(x) | |
| def |-|(y: T): T = Group[T].minus(x, y) | |
| } | |
| def zero[T: Group]: T = Group[T].zero | |
| } |
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 GroupSyntax { | |
| class GroupOps[T: Group](x: T) { ... } | |
| implicit def toGroupOps[T: Group](x: T) = new GroupOps(x) | |
| //... | |
| } |
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 GroupSyntax._ | |
| implicit def PairGroup[T1: Group, T2: Group]: Group[(T1, T2)] = | |
| new GroupAux[(T1, T2)]( | |
| (zero[T1], zero[T2]), | |
| (x, y) => (x._1 |+| y._1, x._2 |+| y._2), | |
| x => (x._1.inverse, x._2.inverse) | |
| ) | |
| def sum[T: Group](elems: Seq[T]): T = elems.foldLeft(zero[T]) { _ |+| _ } | |
| def sumDifference[T: Group](elems1: Seq[T], elems2: Seq[T]): T = | |
| sum(elems1) |-| sum(elems2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment