Commit 072b4b4d authored by Haochen Xie's avatar Haochen Xie

add ch1/Cafe.scala

parent a34eca04
package name.haochenxie.fpscala.ch1
import scala.annotation.tailrec
abstract class CreditCard
case class TestCreditCard(id: Int) extends CreditCard {
override def toString = s"C#$id"
}
object TestCreditCard extends TestCreditCard(0)
case class Coffee() {
def price: Double = 370
}
sealed case class Charge(cc: CreditCard, amount: Double) {
def combine(other: Charge): Charge = Charge.combine(this, other)
}
object Charge {
def combine(a: Charge, b: Charge): Charge =
if (a.cc == b.cc) Charge(a.cc, a.amount + b.amount)
else throw new Exception("Cannot combine charges to different credit cards")
def coalesce(l: List[Charge]): List[Charge] =
l.groupBy(_.cc).values.map(_.reduce(combine)).toList
}
class Cafe {
def buyCoffee(cc: CreditCard): (Coffee, Charge) = {
var cup = new Coffee()
(cup, Charge(cc, cup.price))
}
def buyCoffee(cc: CreditCard, n: Int) : (List[Coffee], Charge) = {
val purchase = List.fill(n)(buyCoffee(cc))
val (coffees, charges) = purchase.unzip
(coffees, charges.reduce((c1, c2) => c1.combine(c2)))
}
}
// === === ===
object CafeScratch {
def main(args: Array[String]) {
val cafe = new Cafe
// println(cafe.buyCoffee(TestCreditCard))
// println(cafe.buyCoffee(TestCreditCard, 12))
val c1 = TestCreditCard(0)
val c2 = TestCreditCard(1)
val l = List(cafe.buyCoffee(c1), cafe.buyCoffee(c1), cafe.buyCoffee(c2, 3))
println(l)
println(Charge.coalesce(l.map(_._2)))
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment