Values and functions#
A billing tool needs an invoice: add up the line items, add shipping unless the order is big enough, and print money like a person would. Here is the whole program.
invoice.ms
fn line_total(price Int, quantity Int = 1) Int {
return price * quantity
}
fn shipping(subtotal Int) Int {
if subtotal >= 4000 {
return 0
}
return 500
}
fn money(cents Int) String {
rest := cents % 100
pad := if rest < 10 { "0" } else { "" }
return f"{cents / 100}.{pad}{rest}"
}
fn main() Void {
prices := [1250, 800, 2500]
var subtotal = 0
for price in prices {
subtotal += line_total(price)
}
discounted := prices.map(price => price - 200)
cheap := discounted.filter(price => price <= 1000)
total := subtotal + shipping(subtotal)
print(f"Subtotal: {money(subtotal)}")
print(f"Shipping: {money(shipping(subtotal))}")
print(f"Total: {money(total)}")
print(f"Items under 10.00 after discount: {cheap.length()}")
}text
Subtotal: 45.50
Shipping: 0.00
Total: 45.50
Items under 10.00 after discount: 1Save it as invoice.ms and run ms run invoice.ms.
What to notice#
:=names a value andvarnames one that changes.subtotalis avarbecause the loop adds to it; everything else is a:=. Types are inferred, so you rarely write them.- A function declares its parameter types and its result type after the parameter list.
quantity Int = 1is a default, soline_total(price)works without the second argument. ifworks as a statement and as an expression:pad := if rest < 10 { "0" } else { "" }picks a value.{expression}inside anf"..."string interpolates any expression, including a function call; plain"..."strings keep braces as written.- A function is a value.
prices.map(price => price - 200)passes a function tomap, andfilterkeeps the items for which a function returnstrue.pricesitself does not change. - Statements need no semicolons.
Try it#
Change the free-shipping threshold in shipping to 5000 and run again. The total grows by the shipping cost.