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 countBeverages(food: Dickmacher) : Int = food match { case Beverage(_, x) => 1 case Food(_, x) => 0 case Meal(_, x, y) => 0 case Combo(a: Food, b) => 0 + countBeverages(b) case Combo(a: Beverage, b) => 1 + countBeverages(b) case Combo(a: Meal, b) => 0 + countBeverages(b) case Combo(a: Combo, b) => 0 + countBeverages(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(countBeverages(cokeCombo)) val burgerCombo = Combo(burger, wannaBeBurger) println(countBeverages(burgerCombo)) val monsterCombo = Combo(Combo(burgerCombo, cokeCombo), Food("Nachspeise", 600)); println(countBeverages(monsterCombo))
Friday, September 28, 2012
Pattern Matching Beverages
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment