Appendix B

The Complete Capstone

Chapter 15 walked the running system in fragments. Here it is whole, in one listing — every region in the order it was built, so the boundaries and the membrane are visible on one page.

This appendix collects the running example into a single coherent program: a tightly-modelled order core, an open pricing engine, a contract membrane between them, fulfillment routing by unification and search, and a thin imperative shell. It is organized bottom-up — leaf types first, orchestration last — so each section depends only on the ones above it.

To keep the listing about the architecture rather than about currency arithmetic and string parsing, two things at the very edges are taken as given, with the exact interface the rest of the code relies on. Everything else is complete.

B.1 Assumed Leaf Types and Boundary Parser

The primitive value types are treated as a small library. Money is an amount with a currency. Its arithmetic is written with the ordinary operators, because a Nex class earns an operator by binding a routine to it: minus declares alias "-", and a - b is then exactly a.minus(b) — precondition and all. That is why same_currency can be a contract on the subtraction rather than a check every caller must remember. The comparisons come the same way, from Comparable's compare, and value equality from equals. Only the zero has no notation: a Nex class has no members of its own, so a zero is made with a constructor and, because an amount of nothing is still an amount of nothing in some currency, it is made in one; the sign predicates is_negative and is_positive spare the contracts from having to conjure one at all. Two further domain operations are used by pricing: less_percent(pct) and times(n). Sku, Email_Address, Tracking_Id, and Instant are opaque identifiers and timestamps.

-- Assumed value types (a small supporting library):
--   Money           : create Money.make(amount: Integer, currency: String)
--                     create Money.zero(currency: String)
--                     plus(m: Money): Money   alias "+"
--                     minus(m: Money): Money  alias "-"
--                       -- both require a matching currency, so + and - carry
--                       -- that precondition wherever they are written
--                     is_negative(): Boolean ; is_positive(): Boolean
--                     less_percent(pct: Integer): Money ; times(n: Integer): Money
--                     .currency: String
--                     inherits Comparable, so = < <= > >= are operators
--   Sku, Email_Address, Tracking_Id, Instant : opaque
--
-- Assumed boundary parser (Chapter 4), built from field parsers like parse_quantity:
--   parse_order(request: Order_Request): Result[Draft, String]
--     -- turns an untrusted request into a validated Draft, or an Err with a reason

B.2 The Constrained Core (Chapters 3–5)

A Quantity cannot be non-positive; a Line_Item pairs a SKU with a quantity and a unit price; an Order is exactly one of three shapes. Placed's invariant is the membrane form from Chapter 15 — a non-negative total in a well-formed order — not the pre-pricing total = sum simplification of Chapter 3.

-- A Quantity is an Integer that is known to be positive (Chapter 3).
declare type Quantity = Integer where n: n > 0

class Line_Item
  create make(s: Sku, q: Quantity, unit: Money) do sku := s  quantity := q  unit_price := unit end
feature
  sku: Sku
  quantity: Quantity
  unit_price: Money
  subtotal(): Money do result := unit_price.times(quantity) end
end

function sum_of(items: Array[Line_Item]): Money
require
  not_empty: items.length > 0
do
  result := create Money.zero(items.get(0).unit_price.currency)
  across items as it do
    result := result + it.subtotal
  end
end

sealed deferred class Order
  create init(xs: Array[Line_Item]) do items := xs end
feature
  items: Array[Line_Item]     -- the one field every state shares
end

class Draft
  inherit Order
  create make(xs: Array[Line_Item], ccy: String, floor: Money,
  email: Email_Address, dest: String)
  do Order.init(xs)  currency := ccy  floor_price := floor
  customer_email := email  zone := dest end
feature
  currency: String
  floor_price: Money
  customer_email: Email_Address
  zone: String
end

class Placed
  inherit Order
  create make(xs: Array[Line_Item], t: Money, email: Email_Address, dest: String)
  require not_empty: xs.length > 0
  do Order.init(xs)  total := t  customer_email := email  zone := dest end
feature
  total: Money
  customer_email: Email_Address
  zone: String
invariant
  not_empty:     items.length > 0
  non_negative:  not total.is_negative()
end

class Shipped
  inherit Order
  create make(xs: Array[Line_Item], t: Tracking_Id) do Order.init(xs)  tracking := t end
feature
  tracking: Tracking_Id
end

-- The one total transition into shipment: you cannot ship what was never placed.
function ship(p: Placed, t: Tracking_Id): Shipped
do
  result := create Shipped.make(p.items, t)
ensure
  items_preserved: result.items = p.items
end

B.3 Result (Chapter 4)

intern data/Result

-- Result[T, E] is one of:
--   Ok(value: T)    -- success, holding a value of type T
--   Err(error: E)   -- failure, holding an error of type E
-- Throughout the capstone the error type E is String.

B.4 The Open Pricing Edge (Chapters 7 & 10)

Pricing is a small open language of expressions evaluated against a Draft, with conditions drawn from a specification algebra. Both interfaces are deferred and unsealed, so new terms and new conditions are added without editing anything.

-- Specifications: an open algebra of conditions on a draft (Chapter 7).
deferred class Spec[T]
  feature holds(item: T): Boolean deferred
end

class Over_Amount inherit Spec[Draft]
  create make(m: Money) do threshold := m end
feature
  threshold: Money
  holds(d: Draft): Boolean do result := sum_of(d.items) >= threshold end
end

-- Pricing expressions: an open language, evaluated to a Money (Chapter 10).
deferred class Price_Expr
  feature eval(d: Draft): Money deferred
end

class Base inherit Price_Expr
  feature eval(d: Draft): Money do result := sum_of(d.items) end
end

class Percent_Off inherit Price_Expr
  create make(pct: Integer, inner: Price_Expr) do percent := pct  base := inner end
feature
  percent: Integer
  base: Price_Expr
  eval(d: Draft): Money
  require valid_percent: percent >= 0 and percent <= 100
  do result := base.eval(d).less_percent(percent)
  ensure no_increase: result <= base.eval(d)
  end
  end

  class When inherit Price_Expr
  create make(s: Spec[Draft], t: Price_Expr, e: Price_Expr)
  do condition := s  yes := t  no := e end
feature
  condition: Spec[Draft]
  yes: Price_Expr
  no: Price_Expr
  eval(d: Draft): Money
  do
    if condition.holds(d) then result := yes.eval(d)
    else result := no.eval(d) end
  end
end

class Floored inherit Price_Expr
  create make(inner: Price_Expr) do base := inner end
feature
  base: Price_Expr
  eval(d: Draft): Money
  do
    let p: Money := base.eval(d)
    if p < d.floor_price then result := d.floor_price else result := p end
    ensure respects_floor: result >= d.floor_price
  end
end

B.5 The Membrane (Chapters 2, 9, 15)

The one gate through which every price, from any rule that will ever exist, must pass to become part of an order. Written from the core's side; it states the terms and admits only what meets them.

function admit_quote(draft: Draft, quote: Money): Result[Placed, String]
require
  same_currency: quote.currency = draft.currency
do
  if quote.is_negative() then
    result := create Err[Placed, String].make("quote is negative")
  elseif quote < draft.floor_price then
    result := create Err[Placed, String].make("quote below floor")
  else
    -- on success, Placed's own invariant guarantees a consistent order
    result := create Ok[Placed, String].make(
      create Placed.make(draft.items, quote, draft.customer_email, draft.zone))
  end
end

B.6 Effects as Data (Chapter 6)

union Effect
  Charge_Payment(amount: Money)
  Reserve_Stock(warehouse: String, items: Array[Line_Item])
  Send_Confirmation(recipient: Email_Address)
  Record_Order(order: Placed)
end

class Placement
feature
  order: Placed
  effects: Array[Effect]
  create make(o: Placed, fx: Array[Effect]) do order := o  effects := fx end
end

B.7 Fulfillment by Unification and Search (Chapter 13)

Terms are a closed structure with open unknowns; unification finds the substitution that makes two terms agree; the search tries each ground route fact against the order's query and keeps the first that satisfies the domain.

union Term
  Var(name: String)
  Atom(value: String)
  Compound(functor: String, args: Array[Term])
end

class Substitution
  create make() do bindings := {} end
feature
  bindings: Map[String, Term]

  bind(vname: String, t: Term): Substitution
  do bindings.put(vname, t)  result := this end

  resolve(t: Term): Term
  do
    match t of
      Var(name) then
        if bindings.contains_key(name) then result := resolve(bindings.get(name))
        else result := t end
      else
        result := t
    end
  end
end

function unify(a: Term, b: Term, s: Substitution): Result[Substitution, String]
do
  let x: Term := s.resolve(a)
  let y: Term := s.resolve(b)
  match x of
    Var(name) then result := create Ok[Substitution, String].make(s.bind(name, y))
    Atom as ax then result := unify_atom(ax, y, s)
    Compound as cx then result := unify_compound(cx, y, s)
  end
end

function unify_atom(ax: Atom, y: Term, s: Substitution): Result[Substitution, String]
do
  match y of
    Var(name) then result := create Ok[Substitution, String].make(s.bind(name, ax))
    Atom(value as v) if v = ax.value then result := create Ok[Substitution, String].make(s)
    Atom(value as v) then result := create Err[Substitution, String].make("clash: " + ax.value + " vs " + v)
    Compound then result := create Err[Substitution, String].make("atom vs structure")
  end
end

function unify_compound(cx: Compound, y: Term, s: Substitution): Result[Substitution, String]
do
  match y of
    Var(name) then result := create Ok[Substitution, String].make(s.bind(name, cx))
    Atom then result := create Err[Substitution, String].make("structure vs atom")
    Compound as cy then
      if cx.functor = cy.functor and cx.args.length = cy.args.length then
        result := unify_args(cx.args, cy.args, s, 0)
      else
        result := create Err[Substitution, String].make("functor / arity mismatch")
      end
  end
end

function unify_args(xs: Array[Term], ys: Array[Term], s: Substitution, i: Integer): Result[Substitution, String]
do
  if i >= xs.length then
    result := create Ok[Substitution, String].make(s)
  else
    match unify(xs.get(i), ys.get(i), s) of
      Ok as ok then result := unify_args(xs, ys, ok.value, i + 1)
      Err as e then result := create Err[Substitution, String].make(e.error)
    end
  end
end

-- The order's routing query: known zone, unknown warehouse/carrier/cost.
function routing_query(o: Placed): Term
do
  let args: Array[Term] := []
  args.add(create Atom.make(o.zone))
  args.add(create Var.make("Warehouse"))
  args.add(create Var.make("Carrier"))
  args.add(create Var.make("Cost"))
  result := create Compound.make("route", args)
end

-- A domain guardrail on a committed solution (a real one checks stock and deadline).
function satisfies_constraints(s: Substitution): Boolean
  do result := s.bindings.contains_key("Warehouse") end

function warehouse_of(s: Substitution): String
do
  match s.resolve(create Var.make("Warehouse")) of
    Atom as a then result := a.value
    else result := "unknown"
  end
end

-- Try each route fact; the first whose bindings satisfy every constraint wins.
function route(query: Term, routes: Array[Term]): Result[Substitution, String]
do
  from
    let i: Integer := 0
    let found: Boolean := false
    result := create Err[Substitution, String].make("no eligible route")
  invariant
    in_range: 0 <= i and i <= routes.length
  variant
    routes.length - i
  until
    i >= routes.length or found
  do
    match unify(query, routes.get(i), create Substitution.make()) of
      Ok as s then
        if satisfies_constraints(s.value) then
          result := create Ok[Substitution, String].make(s.value)
          found := true
        end
      Err then
        do end -- structural mismatch: backtrack, try the next route
    end
    i := i + 1
  end
end

B.8 The Orchestration (Chapter 15)

One pure function threads a request through every region: parse, price, admit, route, and decide the effects. It performs nothing.

function place_order(request: Order_Request, rule: Price_Expr,
                     routes: Array[Term], now: Instant): Result[Placement, String]
do
  match parse_order(request) of                        -- 1. boundary (Ch 4)
    Err as bad then
      result := create Err[Placement, String].make(bad.error)
    Ok as parsed then
      do
        let draft: Draft := parsed.value
        let quote: Money := rule.eval(draft)              -- 2. open edge (Ch 10)
        match admit_quote(draft, quote) of                -- 3. membrane (Ch 2, 9)
          Err as rejected then
            result := create Err[Placement, String].make(rejected.error)
          Ok as ok then
            result := plan_fulfillment(ok.value, routes, now)   -- 4. core decides
        end
      end
  end
end

function plan_fulfillment(placed: Placed, routes: Array[Term],
                          now: Instant): Result[Placement, String]
do
  match route(routing_query(placed), routes) of         -- 4a. routing (Ch 13)
    Err as e then
      result := create Err[Placement, String].make("unfulfillable: " + e.error)
    Ok as sol then
      do
        let fx: Array[Effect] := []                        -- 4b. effects as data (Ch 6)
        fx.add(create Charge_Payment.make(placed.total))
        fx.add(create Reserve_Stock.make(warehouse_of(sol.value), placed.items))
        fx.add(create Send_Confirmation.make(placed.customer_email))
        fx.add(create Record_Order.make(placed))
        result := create Ok[Placement, String].make(create Placement.make(placed, fx))
      end
  end
end

B.9 The Imperative Shell (Chapters 6 & 8)

The only region that touches the world: it calls the pure core, then performs the returned effects. A real deployment wraps this in the logging and metrics layers of Chapter 8; the effect loop itself is this small.

function perform(e: Effect, gateway: Payment_Gateway, mailer: Mailer,
        store: Order_Store, warehouse: Warehouse_Api)
do
  match e of
    Charge_Payment as c then gateway.charge(c.amount)
    Reserve_Stock as r then warehouse.reserve(r.warehouse, r.items)
    Send_Confirmation as s then mailer.send(s.recipient)
    Record_Order as rec then store.save(rec.order)
  end
end

-- Drive one request: decide purely, then perform.
function handle_request(request: Order_Request, rule: Price_Expr, routes: Array[Term],
                        now: Instant, gateway: Payment_Gateway, mailer: Mailer,
                        store: Order_Store, warehouse: Warehouse_Api): Result[Placed, String]
do
  match place_order(request, rule, routes, now) of
    Err as e then
      result := create Err[Placed, String].make(e.error)
    Ok as placement then
      do
        across placement.value.effects as fx do
          perform(fx, gateway, mailer, store, warehouse)
        end
        result := create Ok[Placed, String].make(placement.value.order)
      end
  end
end

B.10 Putting It Together

Finally, the open edge configured as data — a pricing rule and a table of routes — and one request driven through the whole system. Note that every extension point is a value: a new promotion is a new Price_Expr, a new route is a new fact appended to routes, and neither touches the core or the membrane.

-- A pricing rule, as data: 10% off large orders, never below the floor.
let rule: Price_Expr :=
  create Floored.make(
    create When.make(
      create Over_Amount.make(big_order_threshold),
      create Percent_Off.make(10, create Base),
      create Base))

-- Route facts, as data: (zone, warehouse, carrier, cost).
function route_fact(zone: String, wh: String, carrier: String, cost: String): Term
do
  let args: Array[Term] := []
  args.add(create Atom.make(zone))
  args.add(create Atom.make(wh))
  args.add(create Atom.make(carrier))
  args.add(create Atom.make(cost))
  result := create Compound.make("route", args)
end

let routes: Array[Term] := []
-- routes.add(route_fact("zone-a", "wh-1", "ups", "500"))
-- routes.add(route_fact("zone-b", "wh-2", "fedex", "650"))

let outcome: Result[Placed, String] :=
  handle_request(incoming, rule, routes, now,
                 gateway, mailer, store, warehouse)

That is the whole system: a core the compiler proves correct, an edge that grows by adding data, and a single contract holding the two apart and together. Constraint and flexibility, one codebase, no contradiction.