Created
March 12, 2013 10:14
-
-
Save markhibberd/5141767 to your computer and use it in GitHub Desktop.
The consequences of broken laws. Sensible code reviewer, realises you should not use foldRight in scala, so refactors to foldLeft. Mwhahaha.
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
| // Don't try this at home | |
| object BrokenLaws { | |
| trait Monoid[F] { | |
| def zero: F | |
| def append(a: F, b: F): F | |
| } | |
| implicit def DoubleMonoid: Monoid[Double] = new Monoid[Double] { | |
| def zero = 0.0 | |
| def append(a: Double, b: Double) = a + b | |
| } | |
| def sum[A](xs: List[A])(implicit M: Monoid[A]) = | |
| xs.foldRight(M.zero)((a, acc) => M.append(a, acc)) | |
| } | |
| object ContractKiller { | |
| import BrokenLaws._ | |
| def transactions = List(-8.988465674311579E307, 8.988465674311579E307, 1.0) | |
| def main(args: Array[String]) { | |
| val owing = sum(transactions) | |
| if (owing > 0.0) | |
| println("bang!!!") | |
| else | |
| println("have a nice day") | |
| } | |
| } |
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
| // Don't try this at home | |
| object BrokenLaws { | |
| trait Monoid[F] { | |
| def zero: F | |
| def append(a: F, b: F): F | |
| } | |
| implicit def DoubleMonoid: Monoid[Double] = new Monoid[Double] { | |
| def zero = 0.0 | |
| def append(a: Double, b: Double) = a + b | |
| } | |
| def sum[A](xs: List[A])(implicit M: Monoid[A]) = | |
| xs.foldLeft(M.zero)((acc, a) => M.append(a, acc)) | |
| } | |
| object ContractKiller { | |
| import BrokenLaws._ | |
| def transactions = List(-8.988465674311579E307, 8.988465674311579E307, 1.0) | |
| def main(args: Array[String]) { | |
| val owing = sum(transactions) | |
| if (owing > 0.0) | |
| println("bang!!!") | |
| else | |
| println("have a nice day") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment