Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Created March 12, 2013 10:14
Show Gist options
  • Select an option

  • Save markhibberd/5141767 to your computer and use it in GitHub Desktop.

Select an option

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.
// 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")
}
}
// 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