Contracts and generics
Contracts
Section titled “Contracts”A contract is an interface: methods that a type promises to have. A type
adopts it explicitly, with impl Contract for Type, and a method can have
a default body:
import weaver.io.print
contract Shape { fn area(self): Float fn describe(self): String = "a shape of area ${self.area()}"}
type Square = { side: Float }type Circle = { r: Float }
impl Shape for Square { fn area(self) = self.side * self.side}
impl Shape for Circle { fn area(self) = 3.0 * self.r * self.r fn describe(self) = "a circle of radius ${self.r}"}
fn main() { print(Square{side: 2.0}.describe()) print(Circle{r: 1.0}.describe())}a shape of area 4.0a circle of radius 1.0There is no inheritance between types: a type is composed of others, and shares behavior through contracts.
Generics
Section titled “Generics”A type parameter constrained by a contract, <T: Shape>, accepts any type
that adopts it. The function is compiled once per type it is called with,
so the call costs nothing more than a direct one:
import weaver.io.print
fn largest<T: Ord>(xs: T[]): T? { var best: T? = None for x in xs { if best is Some(b) && !(b < x) { continue } best = x } return best}
fn main() { print("${largest([3, 9, 4]) ?? 0}") print("${largest(["pear", "apple", "plum"]) ?? ""}")}9plumOrd is the contract of ordered values, which gives <. A value of any
type that adopts a contract is written any Shape, for an array that
mixes squares and circles: its methods are then found at run time.
Derived contracts
Section titled “Derived contracts”The language’s contracts unlock syntax: Eq gives ==, Ord gives <
and sorting, Hash makes a type a map key, Show writes it in "${…}".
#Eq, #Show and the others write their implementation from the type’s
fields, at compile time:
import weaver.io.print
#Eq #Ord #Showtype Version = { major: Int, minor: Int, patch: Int }
fn main() { val versions = [Version{major: 1, minor: 2, patch: 0}, Version{major: 0, minor: 9, patch: 7}] print("${versions.sorted()}") print("${versions[0] == Version{major: 1, minor: 2, patch: 0}}")}[Version{major: 0, minor: 9, patch: 7}, Version{major: 1, minor: 2, patch: 0}]true#Ord orders the fields in their order of declaration. The code it
generates is ordinary Weaver, which wv expand main.wft shows; the
last chapter shows how to write such a generator.
Generic types
Section titled “Generic types”A record or an enum can take type parameters, and its impl too:
import weaver.io.print
type Stack<T> = { items: T[] }
impl<T> Stack<T> { fn push(mut self, sink x: T) { self.items.push(x) }
fn pop(mut self): T? = self.items.pop()}
fn main() { var s: Stack<String> = Stack{items: []} s.push("a") s.push("b") print(s.pop() ?? "empty")}bmut self marks a method that modifies its receiver, and sink x a
parameter the function keeps, here in its array: the
next chapter explains both.