|
| 1 | +Enum("VendingMachineError") { |
| 2 | + Case("invalidSelection") |
| 3 | + Case("insufficientFunds").associatedValue("coinsNeeded", type: "Int") |
| 4 | + Case("outOfStock") |
| 5 | +} |
| 6 | + |
| 7 | +Class("VendingMachine") { |
| 8 | + Variable(.var, name: "inventory", equals: Literal.dictionary(Dictionary(uniqueKeysWithValues: [ |
| 9 | + ("Candy Bar", Item(price: 12, count: 7)), |
| 10 | + ("Chips", Item(price: 10, count: 4)), |
| 11 | + ("Pretzels", Item(price: 7, count: 11)) |
| 12 | + ]))) |
| 13 | + Variable(.var, name: "coinsDeposited", equals: 0) |
| 14 | + |
| 15 | + Function("vend"){ |
| 16 | + Parameter("name", labeled: "itemNamed", type: "String") |
| 17 | + } _: { |
| 18 | + Guard("let item = inventory[itemNamed]") else: { |
| 19 | + Throw( |
| 20 | + EnumValue("VendingMachineError", case: "invalidSelection") |
| 21 | + ) |
| 22 | + } |
| 23 | + Guard("item.count > 0") else: { |
| 24 | + Throw( |
| 25 | + EnumValue("VendingMachineError", case: "outOfStock") |
| 26 | + ) |
| 27 | + } |
| 28 | + Guard("item.price <= coinsDeposited") else: { |
| 29 | + Throw( |
| 30 | + EnumValue("VendingMachineError", case: "insufficientFunds"){ |
| 31 | + ParameterExp("coinsNeeded", value: Infix("-"){ |
| 32 | + VariableExp("item").property("price") |
| 33 | + VariableExp("coinsDeposited") |
| 34 | + }) |
| 35 | + } |
| 36 | + ) |
| 37 | + } |
| 38 | + Infix("-=", "coinsDeposited", VariableExp("item").property("price")) |
| 39 | + Variable("newItem", equals: VariableExp("item")) |
| 40 | + Infix("-=", "newItem.count", 1) |
| 41 | + Assignment("inventory[itemNamed]", .ref("newItem")) |
| 42 | + Call("print", "Dispensing \\(itemNamed)") |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
0 commit comments