Organizing code#
Orders can hold books and subscriptions, and the total should add up either without caring which is which. An interface names the behavior you need, and a type meets it by having methods that match.
catalog.ms
interface Priced {
fn cents() Int
}
type Book {
title String
pages Int
}
type Subscription {
months Int
}
fn Book.cents() Int {
return 500 + self.pages * 2
}
fn Subscription.cents() Int {
return self.months * 900
}
fn total(items List[Priced]) Int {
var sum = 0
for item in items {
sum += item.cents()
}
return sum
}
fn largest[T Clonable](items List[T], score fn(T) Int) T? {
var best T? = null
var best_score = 0
for item in items {
value := score(item)
if best == null or value > best_score {
best_score = value
best = item.clone()
}
}
return best
}
fn main() Void {
items List[Priced] := [Book("Manuscript", 120), Subscription(6)]
print(f"Cart: {total(items)} cents")
top := largest([3, 9, 4], n => n)
print(f"Largest: {top or 0}")
}text
Cart: 6140 cents
Largest: 9What to notice#
interface Priceddeclares one method.Book.centsis whereBookprovides it; nothing else declares thatBookisPriced. Methods never go inside thetype.totaltakes aList[Priced]and works with any mix of types that implement the interface. It depends on behavior, not on a concrete type.largest[T Clonable]is generic: it works for anyTthat meets its bound, and the compiler checks the bound at every call.Clonableis a bound that says “this type can be cloned with.clone()”. Without it the compiler refusesitem.clone(), because a generic body cannot assume every type has aclone.largestreturnsInt?because an empty list has no largest element;top or 0supplies a fallback fornull.- There is no
anyand no cast. If you need to handle unknown JSON, useJsonValue.
Files are modules#
Each .ms file is a module and export marks what other files can import. Standard APIs come from @std/... and your own code from a relative path:
Manuscript
import line_total from "./pricing.ms"Everything else stays private to its file.
Next: Testing and shipping . Exact rules: Contracts and interfaces , Generics , Modules .