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 simplify(d: Dickmacher) : Dickmacher = { d match { case Combo(Food(x,cal1), Food(y,cal2)) => simplify(Food(x + " mit " + y, cal1 + cal2)) case Combo(Beverage(x,cal1), Beverage(y,cal2)) => simplify(Beverage(x + " mit " + y, cal1 + cal2)) case Combo(a, b) => Combo(simplify(a), simplify(b)) case _ => d } } 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(simplify(cokeCombo)) val burgerCombo = Combo(burger, wannaBeBurger) println(simplify(burgerCombo)) val monsterCombo = Combo(burgerCombo, cokeCombo); println(simplify(monsterCombo))
Friday, September 28, 2012
Pattern Matching Simplify
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment