abstract class Dickmacher case class Beverage (name: String, cal: Int) extends Dickmacher case class Food (name: String, cal: Int) extends Dickmacher case class Meal (name: String, food: Food, drink: Beverage) extends Dickmacher case class Combo (starter: Dickmacher, main: Dickmacher) extends Dickmacher def totalCal(food: Dickmacher) : Int = food match { case Beverage(_, x) => x case Food(_, x) => x case Meal(_, x, y) => x.cal + y.cal case Combo(a: Food, b) => a.cal + totalCal(b) case Combo(a: Beverage, b) => a.cal + totalCal(b) case Combo(a: Meal, b) => totalCal(a) + totalCal(b) case Combo(a: Combo, b) => totalCal(a) + totalCal(b) case _ => throw new AssertionError(); } val coke = Beverage("Cola Light", 50) val burger = Food("Big Mac", 400) val cokeLight = Beverage("Cola", 100) val wannaBeBurger = Food("Veggie Mac", 50) val cokeCombo = Combo(coke, cokeLight) println(totalCal(cokeCombo)) val burgerCombo = Combo(burger, wannaBeBurger) println(totalCal(burgerCombo)) val monsterCombo = Combo(Combo(burgerCombo, cokeCombo), Food("Nachspeise", 600)); println(totalCal(monsterCombo))
Friday, September 28, 2012
Pattern Matching Cal
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment