Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Last active December 15, 2017 21:58
Show Gist options
  • Save yasuabe/f1637d479e2c6bf5c2c99ce2ffd078eb to your computer and use it in GitHub Desktop.
Save yasuabe/f1637d479e2c6bf5c2c99ce2ffd078eb to your computer and use it in GitHub Desktop.
ch01 multi-currency money
package fp_tdd
import org.scalacheck.Prop.forAll
import org.scalacheck.Properties
object Chapter01 extends Properties("Ch01") {
// ======== TODO ========
// $5 + 10 CHF = $10 if rate is 2:1
// Make "amount" private
// Dollar side effect
// Money rounding?
// ======== DONE ========
// 1. $5 * 2 = $10
// product code -------------------------------------------------------------------
class Dollar(var amount: Int) {
def times(multiplier: Int): Unit = amount = amount * multiplier
}
// properties -------------------------------------------------------------------
property("$0 * x = $0") = forAll { (x: Int) =>
val zero: Dollar = new Dollar(0)
zero.times(x)
zero.amount == 0
}
property("$1 * x = $x") = forAll { (x: Int) =>
val five: Dollar = new Dollar(1)
five.times(x)
five.amount == x
}
property("$a * b = $b * a") = forAll { (a: Int, b: Int) =>
val d1: Dollar = new Dollar(a)
d1.times(b)
val d2: Dollar = new Dollar(b)
d2.times(a)
d1.amount == d2.amount
}
property("($a * b) * c = $a * (b * c)") = forAll { (a: Int, b: Int, c: Int) =>
val d1: Dollar = new Dollar(a)
d1.times(b)
d1.times(c)
val d2: Dollar = new Dollar(a)
d2.times(b * c)
d1.amount == d2.amount
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment