Data#
Orders have a customer, an amount, and a status, and the status carries different details depending on what happened. Manuscript models that with a type and an enum.
orders.ms
type Order {
id Int
customer String
cents Int
status Status = Status.Open
}
enum Status {
Open
Shipped(tracking String)
Cancelled(reason String)
}
fn label(status Status) String {
match status {
Open => {
return "waiting to ship"
}
Shipped(tracking) => {
return f"shipped, tracking {tracking}"
}
Cancelled(reason) => {
return f"cancelled: {reason}"
}
}
}
fn main() Void {
var orders = [
Order(1, "Sam", 1250),
Order(2, "Ada", 4000, status: Status.Shipped("ZX81")),
Order(3, "Sam", 3100, status: Status.Cancelled("out of stock")),
]
orders.append(Order(4, "Lin", 900))
var spent = Map[String, Int]()
var customers = Set[String]()
for order in orders {
customers.add(order.customer.clone())
total := spent.get_or(order.customer, 0) + order.cents
spent.add(order.customer.clone(), total)
print(f"#{order.id} {order.customer}: {label(order.status)}")
}
print(f"{customers.length()} customers")
print(f"Sam spent {spent.get_or("Sam", 0)} cents")
}text
#1 Sam: waiting to ship
#2 Ada: shipped, tracking ZX81
#3 Sam: cancelled: out of stock
#4 Lin: waiting to ship
3 customers
Sam spent 4350 centsWhat to notice#
type Ordergroups named fields.status Status = Status.Openis a default, soOrder(1, "Sam", 1250)needs no status. Pass a field by name to override it.enum Statuslists the cases an order can be in.ShippedandCancelledcarry a value;Opendoes not.matchmust cover every case. Add a fourth case toStatusand the compiler points atlabeluntil you handle it.- Lists, maps, and sets need no import.
spent.get_or(key, 0)looks up a customer’s running total and returns0when the key is missing. - A
Setignores duplicates, socustomers.length()counts people, not orders.
You may have noticed .clone() when a customer name is stored in the set and the map. The compiler requires it, and the next chapters explain why: each value has one owner, and putting a name into a second place needs its own copy.
Next: When things go wrong . Exact rules: Types , Collections , Pattern matching .