Last updated: 2026-11-21

U
Undergraduate level

PatLang Showcase: Two Paradigms per Problem

For new readers

Four small programs, each solving one recognisable problem by combining two of PatLang's paradigms: exact numbers with contracts, logic with objects, planning with numbers, and events with objects. Each comes with the same program in Python, written with Python's own standard tools, so the two can be read side by side. No PatLang background is assumed; the Paradigms Guide explains each paradigm on its own. The showcase continues with bounds, streams, worlds and parallel sums, watching, secrets and specifications, replanning, contract coverage and crash-safe work, and programs that combine several paradigms.

Each program here lives in the PatLang repository's showcase/ directory, and the code on this page is that file. PatLang's test gates run every one of them on the interpreter and as native builds for Windows and Linux, and compare what each prints with the output shown below. The Python versions are run the same way and must print the same.same output does not mean same cost or safety

The interest is in where each program puts its effort. In the PatLang version, the policy, the plan's terms or the promise a function makes is written down in the place it applies, in the terms of the problem. In the Python version some of that has to be built first: a planner, an event bus, a search order, an exact rate wrapped at each literal.

A loan and its schedule, to the penny

Exact numbers and design by contract. A loan of 10,000 at 6% a year is repaid in 12 monthly payments. The rate 6/100 is the fraction 3/50, and arithmetic on fractions stays exact, so each function's contract can use ==: after the last exact payment the balance is zero, and the rounded schedule pays back the principal plus exactly the interest it charged. The same calculation in floats ends a fraction of a billionth away from zero, which the last lines show.contracts let you assert invariants, not just types

# A loan and its schedule, to the penny.
#
# Paradigms: exact numbers and design by contract.
#
# A loan of 10,000 at 6% a year, repaid in 12 monthly payments. In PatLang the
# rate 6/100 is the fraction 3/50 exactly, not the nearest binary float to
# 0.06, and arithmetic on fractions stays exact. So the contracts can use ==
# where float code would need a tolerance: after the last payment the balance
# is zero, not "close to zero", and the rounded schedule pays back exactly what
# was lent plus exactly the interest it charged.
#
# The same schedule in floats is printed at the end, for comparison.

# ---- exact arithmetic ----

# x to the power n, for a whole n >= 0, by repeated multiplication: exact for
# any exact x.
make a function called power takes x, n returns p
  require n >= 0
  let p = 1
  let i = 0
  while i < n do
    let p = p * x
    let i = i + 1
  end
  return p
end

# The fixed monthly payment that repays principal over the given months:
# P r / (1 - (1 + r)^-n), with r the monthly rate.
make a function called monthly_payment takes principal, yearly_rate, months returns payment
  require (principal > 0) and (months > 0)
  let r = yearly_rate / 12
  let growth = power(1 + r, months)
  let payment = principal * r * growth / (growth - 1)
  ensure payment * months > principal
  return payment
end

# The exact schedule: each month's interest, and what is left. The contract is
# the point: after the last payment nothing is owed, exactly.
make a function called exact_balance_after takes principal, yearly_rate, months returns balance
  let r = yearly_rate / 12
  let payment = monthly_payment(principal, yearly_rate, months)
  let balance = principal
  let m = 0
  while m < months do
    let balance = balance + balance * r - payment
    let m = m + 1
  end
  ensure balance == 0
  return balance
end

# ---- money in pennies ----

# The nearest whole number to an exact x >= 0 (a half rounds up).
make a function called nearest takes x returns n
  return floor(x + 1 / 2)
end

make a function called money takes pennies returns text
  let pad = ""
  if pennies % 100 < 10 then
    let pad = "0"
  end
  return "" + floor(pennies / 100) + "." + pad + (pennies % 100)
end

# A number to the given places, rounded: for showing an exact value.
make a function called decimal takes x, places returns text
  let scale = power(10, places)
  let n = nearest(x * scale)
  let frac = sb_new()
  let digits = "" + (n % scale)
  let k = digits.length
  while k < places do
    sb_push(frac, "0")
    let k = k + 1
  end
  sb_push(frac, digits)
  return "" + floor(n / scale) + "." + sb_str(frac)
end

# The schedule as a bank prints it, in whole pennies: each month's interest is
# rounded to the penny, and the last payment is whatever clears the balance.
# Its contract: what was paid is exactly what was lent plus the interest
# charged, and nothing is left.
make a function called print_schedule takes principal, yearly_rate, months returns total_paid
  let r = yearly_rate / 12
  let payment = nearest(monthly_payment(principal, yearly_rate, months) * 100)
  let balance = principal * 100
  let total_paid = 0
  let total_interest = 0
  let m = 1
  while m <= months do
    let interest = nearest(balance * r)
    let pay = payment
    if m == months then
      let pay = balance + interest
    end
    let balance = balance + interest - pay
    let total_paid = total_paid + pay
    let total_interest = total_interest + interest
    print("  month " + m + ": interest " + money(interest) + ", paid " + money(pay) + ", owed " + money(balance))
    let m = m + 1
  end
  print("  paid " + money(total_paid) + " in all, of which interest " + money(total_interest))
  ensure (balance == 0) and (total_paid == principal * 100 + total_interest)
  return total_paid
end

# ---- the same in floats ----

make a function called float_balance_after takes principal, yearly_rate, months returns balance
  let r = yearly_rate / 12.0
  let growth = 1.0
  let i = 0
  while i < months do
    let growth = growth * (1.0 + r)
    let i = i + 1
  end
  let payment = principal * r * growth / (growth - 1.0)
  let balance = principal
  let m = 0
  while m < months do
    let balance = balance + balance * r - payment
    let m = m + 1
  end
  return balance
end

# ---- the loan ----

let principal = 10000
let rate = 6 / 100
let months = 12

print("== the rate ==")
print("6/100 is " + rate + ", a " + type_of(rate))
print("1/10 + 2/10 == 3/10: " + (1 / 10 + 2 / 10 == 3 / 10))
print("0.1 + 0.2 == 0.3: " + (0.1 + 0.2 == 0.3))

print("== the exact payment ==")
let exact = monthly_payment(principal, rate, months)
print("monthly payment, to 12 places: " + decimal(exact, 12))
print("owed after 12 exact payments: " + exact_balance_after(principal, rate, months))

print("== the schedule, in pennies ==")
print_schedule(principal, rate, months)

print("== the same in floats ==")
let left = float_balance_after(10000.0, 0.06, 12)
print("owed after 12 float payments: " + left)
print("is it zero? " + (left == 0.0))

Output:

Output (click to expand)
== the rate ==
6/100 is 3/50, a rational
1/10 + 2/10 == 3/10: true
0.1 + 0.2 == 0.3: false
== the exact payment ==
monthly payment, to 12 places: 860.664297070807
owed after 12 exact payments: 0
== the schedule, in pennies ==
  month 1: interest 50.00, paid 860.66, owed 9189.34
  month 2: interest 45.95, paid 860.66, owed 8374.63
  month 3: interest 41.87, paid 860.66, owed 7555.84
  month 4: interest 37.78, paid 860.66, owed 6732.96
  month 5: interest 33.66, paid 860.66, owed 5905.96
  month 6: interest 29.53, paid 860.66, owed 5074.83
  month 7: interest 25.37, paid 860.66, owed 4239.54
  month 8: interest 21.20, paid 860.66, owed 3400.08
  month 9: interest 17.00, paid 860.66, owed 2556.42
  month 10: interest 12.78, paid 860.66, owed 1708.54
  month 11: interest 8.54, paid 860.66, owed 856.42
  month 12: interest 4.28, paid 860.70, owed 0.00
  paid 10327.96 in all, of which interest 327.96
== the same in floats ==
owed after 12 float payments: -0.0000000002461320036672987
is it zero? false

Python does this one well: fractions.Fraction is exact, and the program carries over almost line for line. Exactness is something it opts into at each literal (Fraction(6, 100)), where in PatLang 6/100 is already exact, and the contracts become assert statements, which python -O removes.

The Python version
"""The loan schedule of showcase/p1_loan_schedule.patlang, in Python.

Python does this well: fractions.Fraction is exact, and decimal.Decimal rounds
money the way banks do. The differences are where exactness comes from (an
import and a constructor at each literal, where PatLang's 6/100 is already
exact) and what a contract is (an assert, removed by python -O, where PatLang's
ensure is part of the function and can be kept in a build).

Prints the same lines as the PatLang program.
"""
from decimal import Decimal
from fractions import Fraction
from math import floor


def monthly_payment(principal, yearly_rate, months):
    assert principal > 0 and months > 0
    r = yearly_rate / 12
    growth = (1 + r) ** months
    payment = principal * r * growth / (growth - 1)
    assert payment * months > principal
    return payment


def exact_balance_after(principal, yearly_rate, months):
    r = yearly_rate / 12
    payment = monthly_payment(principal, yearly_rate, months)
    balance = principal
    for _ in range(months):
        balance = balance + balance * r - payment
    assert balance == 0
    return balance


def nearest(x):
    return floor(x + Fraction(1, 2))


def money(pennies):
    return f"{pennies // 100}.{pennies % 100:02d}"


def decimal(x, places):
    scale = 10 ** places
    n = nearest(x * scale)
    return f"{n // scale}.{n % scale:0{places}d}"


def print_schedule(principal, yearly_rate, months):
    r = yearly_rate / 12
    payment = nearest(monthly_payment(principal, yearly_rate, months) * 100)
    balance = principal * 100
    total_paid = total_interest = 0
    for m in range(1, months + 1):
        interest = nearest(balance * r)
        pay = balance + interest if m == months else payment
        balance = balance + interest - pay
        total_paid += pay
        total_interest += interest
        print(f"  month {m}: interest {money(interest)}, paid {money(pay)}, owed {money(balance)}")
    print(f"  paid {money(total_paid)} in all, of which interest {money(total_interest)}")
    assert balance == 0 and total_paid == principal * 100 + total_interest
    return total_paid


def float_balance_after(principal, yearly_rate, months):
    r = yearly_rate / 12.0
    growth = 1.0
    for _ in range(months):  # as the PatLang program does, so the floats match
        growth = growth * (1.0 + r)
    payment = principal * r * growth / (growth - 1.0)
    balance = principal
    for _ in range(months):
        balance = balance + balance * r - payment
    return balance


principal = 10000
rate = Fraction(6, 100)
months = 12

def b(x):
    """A bool as PatLang prints one."""
    return "true" if x else "false"


print("== the rate ==")
print(f"6/100 is {rate}, a rational")
print(f"1/10 + 2/10 == 3/10: {b(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))}")
print(f"0.1 + 0.2 == 0.3: {b(0.1 + 0.2 == 0.3)}")

print("== the exact payment ==")
exact = monthly_payment(principal, rate, months)
print(f"monthly payment, to 12 places: {decimal(exact, 12)}")
print(f"owed after 12 exact payments: {exact_balance_after(principal, rate, months)}")

print("== the schedule, in pennies ==")
print_schedule(principal, rate, months)

print("== the same in floats ==")
left = float_balance_after(10000.0, 0.06, 12)
# PatLang prints a float's shortest round-trip digits without an exponent
print(f"owed after 12 float payments: {format(Decimal(repr(left)), 'f')}")
print(f"is it zero? {b(left == 0.0)}")

Who may do what, and why

Logic programming and objects. People, groups and documents are objects whose methods state facts: ada owns the budget, bob is in finance, finance may edit the budget. Three rules say what follows from those facts, delegation included, and every answer comes with its reason, the rule that gave it and through whom. Adding a fact later changes the answers with no code changed.

# Who may do what, and why.
#
# Paradigms: objects and logic programming.
#
# People, groups and documents are objects with methods, as anywhere. What the
# methods do is state facts: "ada owns the budget", "bob is in finance",
# "finance may edit the budget". Three rules then say what follows, including
# through delegation, and each answer comes with its reason: the rule that gave
# it and through whom. Adding a fact later changes the answers with no code
# changed; the policy itself is the three rules below.
#
# Given --page PATH, the program also writes the policy as it finally stands
# as a web page: a table of people against documents and actions, each cell
# holding its reason, filled by one query per column (lib/dom.patlang).

include "../self_hosting/lib/dom.patlang"

class Org {
  field store = 0
}

class Person {
  field name = ""
  field org = 0
  make a function called join takes self, group returns me
    rule_add_to(self.org.store, "member", [self.name, group.name], [])
    return self
  end
  make a function called owns takes self, doc returns me
    rule_add_to(self.org.store, "owns", [self.name, doc.name], [])
    return self
  end
  # Lets another person do on doc whatever this one may.
  make a function called delegate takes self, to, doc returns me
    require to.name != self.name
    rule_add_to(self.org.store, "delegate", [self.name, to.name, doc.name], [])
    return self
  end
}

class Group {
  field name = ""
  field org = 0
  make a function called grant takes self, action, doc returns me
    rule_add_to(self.org.store, "grant", [self.name, action, doc.name], [])
    return self
  end
}

class Document {
  field name = ""
}

make a function called new_org returns org
  let org = new("Org")
  org.store = logic_store_new()
  using org.store as logic do
    rule action(read).
    rule action(edit).
    rule action(share).
    # An owner may do anything to what they own.
    rule can(U, A, D, owner, U) :- owns(U, D), action(A).
    # A member may do what their group is granted.
    rule can(U, A, D, group, G) :- member(U, G), grant(G, A, D).
    # Whoever is delegated to may do what the delegator may.
    rule can(U, A, D, delegated, V) :- delegate(V, U, D), can(V, A, D, How, Via).
  end
  return org
end

make a function called person takes org, name returns p
  let p = new("Person")
  p.name = name
  p.org = org
  return p
end

make a function called group takes org, name returns g
  let g = new("Group")
  g.name = name
  g.org = org
  return g
end

make a function called document takes name returns d
  let d = new("Document")
  d.name = name
  return d
end

# Each person who may do action to doc, with the reason, one a line.
make a function called who_may takes org, action, doc returns n
  let sols = solve_in(org.store, "can", [logic_var("Who"), action, doc.name, logic_var("How"), logic_var("Via")])
  print("who may " + action + " the " + doc.name + ":")
  if list_len(sols) == 0 then
    print("  nobody")
  end
  let i = 0
  while i < list_len(sols) do
    let s = sols[i]
    print("  " + s[0] + ", as " + s[3] + " (" + s[4] + ")")
    let i = i + 1
  end
  return list_len(sols)
end

# Whether one person may, and if not, that no rule says so.
make a function called may takes org, who, action, doc returns yes
  let sols = solve_in(org.store, "can", [who.name, action, doc.name, logic_var("How"), logic_var("Via")])
  let yes = list_len(sols) > 0
  if yes then
    print(who.name + " may " + action + " the " + doc.name + ", as " + sols[0][3])
  else
    print(who.name + " may not " + action + " the " + doc.name + ": no rule gives it")
  end
  return yes
end

# ---- the page: everyone against every document and action ----

make a function called access_page takes org, people, docs, actions returns page
  let page = dom_page("Who may do what")
  let body = dom_body(page)
  dom_set_text(dom_append(body, dom_element("h1")), "Who may do what")
  let table = dom_append(body, dom_element("table"))
  let docs_row = dom_append(table, dom_element("tr"))
  let actions_row = dom_append(table, dom_element("tr"))
  dom_append(docs_row, dom_element("th"))
  dom_append(actions_row, dom_element("th"))
  let d = 0
  while d < list_len(docs) do
    let th = dom_set_text(dom_append(docs_row, dom_element("th")), docs[d].name)
    dom_set_attr(th, "colspan", "" + list_len(actions))
    let a = 0
    while a < list_len(actions) do
      dom_set_text(dom_append(actions_row, dom_element("th")), actions[a])
      let a = a + 1
    end
    let d = d + 1
  end
  # every cell starts as no
  let p = 0
  while p < list_len(people) do
    let row = dom_append(table, dom_element("tr"))
    dom_set_text(dom_append(row, dom_element("th")), people[p].name)
    let d2 = 0
    while d2 < list_len(docs) do
      let a2 = 0
      while a2 < list_len(actions) do
        let td = dom_set_text(dom_append(row, dom_element("td")), "no")
        dom_set_attr(td, "id", people[p].name + "-" + actions[a2] + "-" + docs[d2].name)
        dom_set_attr(td, "class", "no")
        let a2 = a2 + 1
      end
      let d2 = d2 + 1
    end
    let p = p + 1
  end
  # one query per column: everyone who may, with the first reason found
  let d3 = 0
  while d3 < list_len(docs) do
    let a3 = 0
    while a3 < list_len(actions) do
      let sols = solve_in(org.store, "can", [logic_var("Who"), actions[a3], docs[d3].name, logic_var("How"), logic_var("Via")])
      let s = 0
      while s < list_len(sols) do
        let td = dom_by_id(page, sols[s][0] + "-" + actions[a3] + "-" + docs[d3].name)
        if dom_has_class(td, "no") then
          dom_set_attr(td, "class", "yes")
          dom_set_text(td, sols[s][3] + " (" + sols[s][4] + ")")
        end
        let s = s + 1
      end
      let a3 = a3 + 1
    end
    let d3 = d3 + 1
  end
  return page
end

let org = new_org()
let ada = person(org, "ada")
let bob = person(org, "bob")
let carol = person(org, "carol")
let dan = person(org, "dan")
let finance = group(org, "finance")
let budget = document("budget")
let roadmap = document("roadmap")

ada.owns(budget)
bob.join(finance)
finance.grant("read", budget)
finance.grant("edit", budget)
dan.owns(roadmap)
dan.delegate(carol, roadmap)

print("== the policy, applied ==")
who_may(org, "edit", budget)
who_may(org, "share", roadmap)
may(org, carol, "edit", budget)

print("== carol joins finance ==")
carol.join(finance)
may(org, carol, "edit", budget)
who_may(org, "read", budget)

print("== ada delegates the budget to dan ==")
ada.delegate(dan, budget)
may(org, dan, "share", budget)

let args = argv()
if (list_len(args) == 2) and (args[0] == "--page") then
  let page = access_page(org, [ada, bob, carol, dan], [budget, roadmap], ["read", "edit", "share"])
  write_file(args[1], dom_document_html(page))
end

Output:

== the policy, applied ==
who may edit the budget:
  ada, as owner (ada)
  bob, as group (finance)
who may share the roadmap:
  dan, as owner (dan)
  carol, as delegated (dan)
carol may not edit the budget: no rule gives it
== carol joins finance ==
carol may edit the budget, as group
who may read the budget:
  ada, as owner (ada)
  bob, as group (finance)
  carol, as group (finance)
== ada delegates the budget to dan ==
dan may share the budget, as delegated

Given --page PATH, the program also writes its answers as a page: a matrix of people against documents and actions, one query per column, each cell holding the reason or a plain no. It builds the page as a document tree with lib/dom.patlang, which escapes every text node as it writes, so a name in the facts can never turn into markup.

The page it writes:

The Python version keeps the facts as sets of tuples, which suits Python well, and turns the three rules into a function that answers one question: who may do this, and why. The search order is written out by hand, and a different question, such as what bob may do, or on which documents, needs another function. The PatLang program asks those of the same three rules by leaving a different argument open.one query, many questions via open arguments

The Python version
"""The access rules of showcase/p2_access_rules.patlang, in Python.

The facts are sets of tuples, as a Python programmer would keep them, and the
three rules become one function that answers "who may do this, and why". The
function is the policy; in the PatLang program the policy is the three rules
and the search is the language's. Here the search order is written by hand,
and asking a different question (what may bob do? on which documents?) needs
another function, or this one generalised; the PatLang program asks those of
the same three rules by leaving a different argument unbound.

Prints the same lines as the PatLang program.
"""

ACTIONS = ["read", "edit", "share"]


class Org:
    def __init__(self):
        self.owns = []        # (person, doc)
        self.member = []      # (person, group)
        self.grant = []       # (group, action, doc)
        self.delegate = []    # (from, to, doc)

    def can(self, action, doc, who=None):
        """Every (who, how, via) that may do action to doc, or only those for
        one person, in the order the PatLang program's rules give them."""
        out = []
        for p, d in self.owns:
            if d == doc and action in ACTIONS and who in (None, p):
                out.append((p, "owner", p))
        for p, g in self.member:
            for g2, a, d in self.grant:
                if g2 == g and a == action and d == doc and who in (None, p):
                    out.append((p, "group", g))
        for frm, to, d in self.delegate:
            if d == doc and who in (None, to):
                # one answer for each reason the delegator has
                for _ in self.can(action, doc, frm):
                    out.append((to, "delegated", frm))
        return out


class Person:
    def __init__(self, org, name):
        self.org, self.name = org, name

    def join(self, group):
        self.org.member.append((self.name, group.name))
        return self

    def owns(self, doc):
        self.org.owns.append((self.name, doc.name))
        return self

    def delegate(self, to, doc):
        assert to.name != self.name
        self.org.delegate.append((self.name, to.name, doc.name))
        return self


class Group:
    def __init__(self, org, name):
        self.org, self.name = org, name

    def grant(self, action, doc):
        self.org.grant.append((self.name, action, doc.name))
        return self


class Document:
    def __init__(self, name):
        self.name = name


def who_may(org, action, doc):
    sols = org.can(action, doc.name)
    print(f"who may {action} the {doc.name}:")
    if not sols:
        print("  nobody")
    for who, how, via in sols:
        print(f"  {who}, as {how} ({via})")
    return len(sols)


def may(org, who, action, doc):
    sols = org.can(action, doc.name, who.name)
    if sols:
        print(f"{who.name} may {action} the {doc.name}, as {sols[0][1]}")
    else:
        print(f"{who.name} may not {action} the {doc.name}: no rule gives it")
    return bool(sols)


org = Org()
ada, bob, carol, dan = (Person(org, n) for n in ["ada", "bob", "carol", "dan"])
finance = Group(org, "finance")
budget, roadmap = Document("budget"), Document("roadmap")

ada.owns(budget)
bob.join(finance)
finance.grant("read", budget)
finance.grant("edit", budget)
dan.owns(roadmap)
dan.delegate(carol, roadmap)

print("== the policy, applied ==")
who_may(org, "edit", budget)
who_may(org, "share", roadmap)
may(org, carol, "edit", budget)

print("== carol joins finance ==")
carol.join(finance)
may(org, carol, "edit", budget)
who_may(org, "read", budget)

print("== ada delegates the budget to dan ==")
ada.delegate(dan, budget)
may(org, dan, "share", budget)

A small factory, planned

Goal-oriented planning and numbers. Steel is cut into blanks, a press turns a blank into a widget using power from a battery that must be charged, and widgets can also be bought in. Each action states what it needs and what it changes, in facts (the press is on) and in numbers (steel at least 1, power down by 2), and what it costs. The planner finds the cheapest order of actions that reaches a goal such as "at least 3 widgets"; no step order is written anywhere in the program.

# A small factory, planned.
#
# Paradigms: goal-oriented planning and numbers.
#
# A workshop makes widgets: steel is cut into blanks, and a press turns a blank
# into a widget using power from a battery that must be charged. Steel can be
# bought, the press must be switched on first, and widgets can also be bought
# in, at a price. Each action says what it needs and what it changes, in facts
# ("the press is on") and in numbers ("steel >= 1", "power -= 2"). The planner
# finds the cheapest order of actions that reaches a goal such as "at least 3
# widgets". No step order is written anywhere in the program.
#
# The fluents are kept bounded (steel below 2 to buy more, power below 4 to
# charge), so the planner's search space is finite.
#
# Given --page PATH, the program also writes its plans as a web page: a row
# per goal, each step a cell coloured by its kind (lib/dom.patlang).

include "../self_hosting/lib/dom.patlang"

# What each action costs, as given to action_add below, to total a plan.
make a function called cost_of takes name returns c
  match name do
    case "switch_on" then
      return 1
    case "switch_off" then
      return 1
    case "buy_steel" then
      return 4
    case "cut" then
      return 1
    case "charge" then
      return 1
    case "press" then
      return 2
    case "buy_widget" then
      return 7
    case _ then
      return 0
  end
end

make a function called plan_cost takes steps returns total
  let total = 0
  let i = 0
  while i < list_len(steps) do
    let total = total + cost_of(step_name(steps[i]))
    let i = i + 1
  end
  return total
end

# What kind of step an action is, for the page's colours.
make a function called kind_of takes name returns kind
  if substr(name, 0, 4) == "buy_" then
    return "buy"
  end
  if (name == "cut") or (name == "press") then
    return "make"
  end
  return "machine"
end

# The page: a row per goal, its cost, then its steps.
make a function called plans_page takes plans returns page
  let page = dom_page("The factory's plans")
  let style = dom_append(dom_by_tag(page, "head")[0], dom_element("style"))
  dom_set_text(style, "td.machine { background: #bfdbfe } td.make { background: #bbf7d0 } td.buy { background: #fde68a }")
  let body = dom_body(page)
  dom_set_text(dom_append(body, dom_element("h1")), "The factory's plans")
  let table = dom_append(body, dom_element("table"))
  let head = dom_append(table, dom_element("tr"))
  dom_set_text(dom_append(head, dom_element("th")), "goal")
  dom_set_text(dom_append(head, dom_element("th")), "cost")
  dom_set_text(dom_append(head, dom_element("th")), "steps")
  let i = 0
  while i < vec_len(plans) do
    let goal = vec_get(plans, i)[0]
    let steps = vec_get(plans, i)[1]
    let row = dom_append(table, dom_element("tr"))
    dom_set_text(dom_append(row, dom_element("th")), goal)
    dom_set_attr(dom_set_text(dom_append(row, dom_element("td")), "" + plan_cost(steps)), "class", "cost")
    let j = 0
    while j < list_len(steps) do
      let name = step_name(steps[j])
      dom_set_attr(dom_set_text(dom_append(row, dom_element("td")), name), "class", kind_of(name))
      let j = j + 1
    end
    let i = i + 1
  end
  return page
end

# Prints the plan for goal, and keeps it for the page.
make a function called show_plan takes plans, goal, steps returns steps
  print("== " + goal + " ==")
  print(describe(steps))
  vec_push(plans, [goal, steps])
  return steps
end

make a function called describe takes steps returns text
  let total = plan_cost(steps)
  let noun = " steps: "
  if list_len(steps) == 1 then
    let noun = " step: "
  end
  return "cost " + total + ", " + list_len(steps) + noun + plan_labels(steps)
end

fluent_set("steel", 1)
fluent_set("blanks", 0)
fluent_set("power", 0)
fluent_set("widgets", 0)

# action_add_numeric(name, facts needed, numbers needed, facts added,
#                    facts removed, number changes, cost)
action_add("switch_on", [], [["on", ["press"]]], [], 1)
action_add_numeric("buy_steel", [], [["steel", "<", 2]], [], [], [["steel", "+=", 1]], 4)
action_add_numeric("cut", [], [["steel", ">=", 1]], [], [], [["steel", "-=", 1], ["blanks", "+=", 1]], 1)
action_add_numeric("charge", [], [["power", "<", 4]], [], [], [["power", "+=", 2]], 1)
action_add_numeric("press", [["on", ["press"]]], [["blanks", ">=", 1], ["power", ">=", 2]], [], [], [["blanks", "-=", 1], ["power", "-=", 2], ["widgets", "+=", 1]], 2)
action_add_numeric("buy_widget", [], [], [], [], [["widgets", "+=", 1]], 7)

# Making a widget from the steel in stock costs 5 (switch on, cut, charge,
# press); each further one needs steel bought first, 8, more than buying a
# widget in at 7. So the cheapest way to three makes one and buys two.
let plans = vec_new()
show_plan(plans, "one widget", plan_numeric([], [["widgets", ">=", 1]]))
show_plan(plans, "three widgets", plan_numeric([], [["widgets", ">=", 3]]))

# A fact goal and a number goal together: the plan must end with the press
# off, which needs an action that removes the fact.
action_add("switch_off", [["on", ["press"]]], [["off", ["press"]]], [["on", ["press"]]], 1)
show_plan(plans, "three widgets, and the press switched off again", plan_numeric([["off", ["press"]]], [["widgets", ">=", 3]]))

# The same actions from another starting state: making one would now cost 9,
# so the plan buys it in. Only the number changed.
fluent_set("steel", 0)
show_plan(plans, "one widget, starting with no steel", plan_numeric([], [["widgets", ">=", 1]]))

let args = argv()
if (list_len(args) == 2) and (args[0] == "--page") then
  write_file(args[1], dom_document_html(plans_page(plans)))
end

Output:

== one widget ==
cost 5, 4 steps: [switch_on, cut, charge, press]
== three widgets ==
cost 19, 6 steps: [switch_on, cut, charge, press, buy_widget, buy_widget]
== three widgets, and the press switched off again ==
cost 20, 7 steps: [switch_on, cut, charge, press, switch_off, buy_widget, buy_widget]
== one widget, starting with no steel ==
cost 7, 1 step: [buy_widget]

With --page PATH each plan becomes a row of its steps, coloured by kind (machine, making, buying), with the plan's cost beside it.

The page it writes:

Python has no planner in its standard library, so its version writes one: a uniform-cost search over states with heapq, each action a test, an effect and a cost. That search is the part the PatLang program gets from plan_numeric, and the actions themselves read much the same in both.uniform-cost search finds the cheapest path

The Python version
"""The factory of showcase/p3_factory_plan.patlang, in Python.

Python has no planner of its own. The usual choices are a PDDL planner run as
a separate program (the domain and problem written out as PDDL text, the plan
read back) or a search written by hand. This is the second: a uniform-cost
search with heapq over states of facts and numbers, written before the
factory itself is described. The PatLang program states the actions and
asks; the search is the language's.

Prints each plan's cost and steps. Plans of equal cost can list their steps
in a different order from the PatLang program's, so the costs are what the two
are compared on.
"""
import heapq
import itertools

OPS = {"<": lambda a, b: a < b, "<=": lambda a, b: a <= b, ">": lambda a, b: a > b,
       ">=": lambda a, b: a >= b, "==": lambda a, b: a == b, "!=": lambda a, b: a != b}
EFFECTS = {"=": lambda a, b: b, "+=": lambda a, b: a + b, "-=": lambda a, b: a - b,
           "*=": lambda a, b: a * b}


class Action:
    def __init__(self, name, needs, num_needs, adds, dels, changes, cost):
        self.name, self.needs, self.num_needs = name, set(needs), num_needs
        self.adds, self.dels, self.changes, self.cost = set(adds), set(dels), changes, cost

    def applies(self, facts, nums):
        return self.needs <= facts and all(
            f in nums and OPS[op](nums[f], v) for f, op, v in self.num_needs)

    def apply(self, facts, nums):
        nums = dict(nums)
        for f, op, v in self.changes:
            nums[f] = EFFECTS[op](nums.get(f, 0), v)
        return (facts - self.dels) | self.adds, nums


def plan(actions, facts, nums, goal_facts, goal_nums):
    """The cheapest list of actions from the state to the goals, or None."""
    tie = itertools.count()
    start = (frozenset(facts), tuple(sorted(nums.items())))
    frontier = [(0, next(tie), start, [])]
    seen = set()
    while frontier:
        cost, _, state, steps = heapq.heappop(frontier)
        if state in seen:
            continue
        seen.add(state)
        f, n = set(state[0]), dict(state[1])
        if set(goal_facts) <= f and all(OPS[op](n.get(k, 0), v) for k, op, v in goal_nums):
            return cost, steps
        for a in actions:
            if a.applies(f, n):
                f2, n2 = a.apply(f, n)
                nxt = (frozenset(f2), tuple(sorted(n2.items())))
                if nxt not in seen:
                    heapq.heappush(frontier, (cost + a.cost, next(tie), nxt, steps + [a.name]))
    return None


def describe(result):
    cost, steps = result
    noun = "step" if len(steps) == 1 else "steps"
    return f"cost {cost}, {len(steps)} {noun}: [{', '.join(steps)}]"


nums = {"steel": 1, "blanks": 0, "power": 0, "widgets": 0}
actions = [
    Action("switch_on", [], [], ["press on"], [], [], 1),
    Action("buy_steel", [], [("steel", "<", 2)], [], [], [("steel", "+=", 1)], 4),
    Action("cut", [], [("steel", ">=", 1)], [], [], [("steel", "-=", 1), ("blanks", "+=", 1)], 1),
    Action("charge", [], [("power", "<", 4)], [], [], [("power", "+=", 2)], 1),
    Action("press", ["press on"], [("blanks", ">=", 1), ("power", ">=", 2)], [], [],
           [("blanks", "-=", 1), ("power", "-=", 2), ("widgets", "+=", 1)], 2),
    Action("buy_widget", [], [], [], [], [("widgets", "+=", 1)], 7),
]

print("== one widget ==")
print(describe(plan(actions, set(), nums, [], [("widgets", ">=", 1)])))

print("== three widgets ==")
print(describe(plan(actions, set(), nums, [], [("widgets", ">=", 3)])))

print("== three widgets, and the press switched off again ==")
actions.append(Action("switch_off", ["press on"], [], ["press off"], ["press on"], [], 1))
print(describe(plan(actions, set(), nums, ["press off"], [("widgets", ">=", 3)])))

print("== one widget, starting with no steel ==")
nums["steel"] = 0
print(describe(plan(actions, set(), nums, [], [("widgets", ">=", 1)])))

A spreadsheet that recalculates itself

Events and objects. Each cell is an object, and its set method declares that it raises the event changed, so every edit is announced without the method calling anyone. Separate handlers do separate jobs: one keeps an audit trail, one recalculates the cells that depend on the edited one, in dependency order, and refuses a change that would make a cycle, putting the old formula back. The cells know nothing of either job, and a third handler could be added without touching them. Values are exact, so a third of 12.50 is 25/6.

# A spreadsheet that recalculates itself.
#
# Paradigms: objects and events.
#
# Each cell is an object. Its set method declares that it raises the event
# changed, so every edit is announced with the cell, the new value and the
# result, without the method calling anyone. Separate handlers then do
# separate jobs: one keeps an audit trail of edits, one recalculates the cells
# that depend on the edited one, in dependency order, and refuses a cycle. The
# cells know nothing of either job, and a third handler could be added without
# touching them.
#
# Values are exact: a fifth of 10 is 2, and a third of 12.50 is 25/6, not
# 4.166666666666667.
#
# Given --page PATH, the program also writes the sheet as a web page: a table
# built as a tree of nodes (lib/dom.patlang), which one more handler keeps up
# to date after each recalculation. The writer escapes every value as it
# writes the page.

include "../self_hosting/lib/dom.patlang"

class Cell {
  field name = ""
  field value = 0
  field inputs = []
  field formula = 0
  field old_inputs = []
  field old_formula = 0
  make a function called set takes self, v returns value raises changed
    self.value = v
    return v
  end
  # A new formula over new inputs: announced as a change like any other. The
  # one it replaces is kept, so a refused change can be undone.
  make a function called redefine takes self, inputs, f returns value raises changed
    self.old_inputs = self.inputs
    self.old_formula = self.formula
    self.inputs = inputs
    self.formula = f
    return self.value
  end
  make a function called undo_redefine takes self returns value
    self.inputs = self.old_inputs
    self.formula = self.old_formula
    return self.value
  end
}

make a function called has takes items, x returns yes
  let i = 0
  while i < list_len(items) do
    if items[i] == x then
      return true
    end
    let i = i + 1
  end
  return false
end

make a function called find takes sheet, name returns c
  let i = 0
  while i < vec_len(sheet) do
    let c = vec_get(sheet, i)
    if c.name == name then
      return c
    end
    let i = i + 1
  end
  # a formula naming a cell the sheet does not have
  assert false
  return c
end

make a function called cell takes sheet, name, value returns c
  let c = new("Cell")
  c.name = name
  c.value = value
  vec_push(sheet, c)
  return c
end

# A cell's value from its formula and its inputs' values, set directly: a
# recalculation is not an edit, so it raises nothing.
make a function called recompute takes sheet, c returns v
  let vals = []
  let i = 0
  while i < list_len(c.inputs) do
    let vals = list_push(vals, find(sheet, c.inputs[i]).value)
    let i = i + 1
  end
  let f = c.formula
  c.value = f(vals)
  return c.value
end

make a function called formula_cell takes sheet, name, inputs, f returns c
  let c = cell(sheet, name, 0)
  c.inputs = inputs
  c.formula = f
  recompute(sheet, c)
  return c
end

# Depth first from name through the cells that read it. Each cell goes into
# order after everything that depends on it; a cell met again on the current
# path is a cycle, given back as the path.
make a function called visit takes sheet, name, done, order, path returns cycle
  let i = 0
  while i < vec_len(sheet) do
    let c = vec_get(sheet, i)
    if has(c.inputs, name) then
      if has(path, c.name) then
        return list_push(path, c.name)
      end
      if not has(vec_to_list(done), c.name) then
        let cycle = visit(sheet, c.name, done, order, list_push(path, c.name))
        if list_len(cycle) > 0 then
          return cycle
        end
      end
    end
    let i = i + 1
  end
  vec_push(done, name)
  vec_push(order, name)
  return []
end

# Recalculates name itself, when it has a formula, and everything that
# depends on it, each cell after its inputs: the names recalculated, or the
# cycle found. A cycle can come only from a new formula, which is undone, so
# the sheet is as it was.
make a function called recalc takes sheet, name returns result
  let done = vec_new()
  let order = vec_new()
  let cycle = visit(sheet, name, done, order, [name])
  if list_len(cycle) > 0 then
    find(sheet, name).undo_redefine()
    emit("cycle", cycle)
    return cycle
  end
  let names = []
  # order ends with name itself, which is recalculated only if it has a formula
  let k = vec_len(order) - 1
  while k >= 0 do
    let c = find(sheet, vec_get(order, k))
    if list_len(c.inputs) > 0 then
      recompute(sheet, c)
      let names = list_push(names, c.name + "=" + c.value)
    end
    let k = k - 1
  end
  emit("recalculated", names)
  return names
end

make a function called show takes sheet returns text
  let parts = []
  let i = 0
  while i < vec_len(sheet) do
    let c = vec_get(sheet, i)
    let parts = list_push(parts, c.name + "=" + c.value)
    let i = i + 1
  end
  return str_join(parts, "  ")
end

# ---- the page: a row per cell, its inputs and its value ----

make a function called page_new returns page
  let page = dom_page("The sheet")
  let body = dom_body(page)
  dom_append(body, dom_element("h1"))
  dom_set_text(dom_by_tag(page, "h1")[0], "The sheet")
  let table = dom_append(body, dom_element("table"))
  let head = dom_append(table, dom_element("tr"))
  dom_set_text(dom_append(head, dom_element("th")), "cell")
  dom_set_text(dom_append(head, dom_element("th")), "from")
  dom_set_text(dom_append(head, dom_element("th")), "value")
  dom_set_attr(dom_append(body, dom_element("p")), "id", "edits")
  return page
end

# Each cell's row, made the first time it is seen, then its inputs and value
# brought up to date, and the count of edits.
make a function called page_refresh takes page, sheet, audit returns page
  let table = dom_by_tag(page, "table")[0]
  let i = 0
  while i < vec_len(sheet) do
    let c = vec_get(sheet, i)
    let row = dom_by_id(page, "row-" + c.name)
    if row == false then
      let row = dom_append(table, dom_element("tr"))
      dom_set_attr(row, "id", "row-" + c.name)
      dom_set_text(dom_append(row, dom_element("td")), c.name)
      dom_set_attr(dom_append(row, dom_element("td")), "class", "from")
      dom_set_attr(dom_append(row, dom_element("td")), "class", "value")
    end
    dom_set_text(dom_by_class(row, "from")[0], str_join(c.inputs, ", "))
    dom_set_text(dom_by_class(row, "value")[0], "" + c.value)
    let i = i + 1
  end
  let n = vec_len(audit)
  if n > 0 then
    dom_set_text(dom_by_id(page, "edits"), "" + n + " edits asked for, the last: " + vec_get(audit, n - 1))
  end
  return page
end

let sheet = vec_new()
let audit = vec_new()
let page = page_new()

# ---- the handlers: each one job ----

# event_data is the cell, the method's arguments, then its result: set has
# one argument, redefine two
when changed do
  let c = event_data[0]
  if list_len(event_data) == 3 then
    vec_push(audit, c.name + " set to " + event_data[1])
  else
    vec_push(audit, c.name + " given a formula over " + str_join(event_data[1], ", "))
  end
end

when changed do
  recalc(sheet, event_data[0].name)
end

when recalculated do
  print("  recalculated: " + str_join(event_data, ", "))
end

when cycle do
  print("  refused, a cycle: " + str_join(event_data, " -> "))
end

when recalculated do
  page_refresh(page, sheet, audit)
end

# ---- the sheet: a net price, its VAT at a fifth, the gross, split three ways ----

let net = cell(sheet, "net", 10)
let vat = formula_cell(sheet, "vat", ["net"], |v| { return v[0] / 5 })
let gross = formula_cell(sheet, "gross", ["net", "vat"], |v| { return v[0] + v[1] })
let share = formula_cell(sheet, "share", ["gross"], |v| { return v[0] / 3 })

print("== the sheet ==")
print(show(sheet))

print("== net set to 125/12 ==")
net.set(125 / 12)
print(show(sheet))

print("== VAT changed to a sixth ==")
vat.redefine(["net"], |v| { return v[0] / 6 })
print(show(sheet))

print("== net redefined from share: a cycle ==")
net.redefine(["share"], |v| { return v[0] * 2 })
print(show(sheet))

print("== net set to 20: the refused formula is gone, so this recalculates ==")
net.set(20)
print(show(sheet))

print("== the audit trail, every edit asked for ==")
print(str_join(vec_to_list(audit), chr(10)))

let args = argv()
if (list_len(args) == 2) and (args[0] == "--page") then
  write_file(args[1], dom_document_html(page_refresh(page, sheet, audit)))
end

Output:

== the sheet ==
net=10  vat=2  gross=12  share=4
== net set to 125/12 ==
  recalculated: vat=25/12, gross=25/2, share=25/6
net=125/12  vat=25/12  gross=25/2  share=25/6
== VAT changed to a sixth ==
  recalculated: vat=125/72, gross=875/72, share=875/216
net=125/12  vat=125/72  gross=875/72  share=875/216
== net redefined from share: a cycle ==
  refused, a cycle: net -> vat -> gross -> share -> net
net=125/12  vat=125/72  gross=875/72  share=875/216
== net set to 20: the refused formula is gone, so this recalculates ==
  recalculated: vat=10/3, gross=70/3, share=70/9
net=20  vat=10/3  gross=70/3  share=70/9
== the audit trail, every edit asked for ==
net set to 125/12
vat given a formula over net
net given a formula over share
net set to 20

The page is one more handler. On recalculated it updates the nodes for the sheet's table, and the cells still know nothing of it: --page PATH writes the tree as it stands after the last edit.

The page it writes:

Python has no events in the language, so its cells carry an observer list and each edit calls the observers itself: set and redefine each end with a call to announce the change. In PatLang the methods say raises changed in their declarations and contain no such call.the observer pattern: objects call watchers directly

The Python version
"""The spreadsheet of showcase/p4_spreadsheet.patlang, in Python.

Python has no events in the language, so the cells carry an observer list
and each edit calls the observers itself: set and redefine each end with a
call to self._announce. The PatLang Cell's methods say "raises changed" in
their declarations and contain no such call. Exact values come from
fractions.Fraction, which Python does well; the literals need wrapping
(Fraction(125, 12)), where PatLang's 125 / 12 is already exact.

Prints the same lines as the PatLang program.
"""
from fractions import Fraction


class Events:
    """A minimal event bus: what `when` and `emit` give the PatLang program."""

    def __init__(self):
        self.handlers = {}

    def when(self, name, f):
        self.handlers.setdefault(name, []).append(f)

    def emit(self, name, data):
        for f in self.handlers.get(name, []):
            f(data)


class Cell:
    def __init__(self, events, name, value):
        self.events, self.name, self.value = events, name, value
        self.inputs, self.formula = [], None

    def _announce(self, *data):
        self.events.emit("changed", [self, *data])

    def set(self, v):
        self.value = v
        self._announce(v, v)
        return v

    def redefine(self, inputs, f):
        self.old_inputs, self.old_formula = self.inputs, self.formula
        self.inputs, self.formula = inputs, f
        self._announce(inputs, f, self.value)
        return self.value

    def undo_redefine(self):
        self.inputs, self.formula = self.old_inputs, self.old_formula
        return self.value


def fmt(x):
    """A value as PatLang prints it: a whole fraction as an int."""
    if isinstance(x, Fraction) and x.denominator == 1:
        return str(x.numerator)
    return str(x)


class Sheet:
    def __init__(self, events):
        self.events, self.cells = events, []

    def find(self, name):
        for c in self.cells:
            if c.name == name:
                return c
        raise KeyError(name)

    def cell(self, name, value):
        c = Cell(self.events, name, value)
        self.cells.append(c)
        return c

    def recompute(self, c):
        c.value = c.formula([self.find(n).value for n in c.inputs])
        return c.value

    def formula_cell(self, name, inputs, f):
        c = self.cell(name, 0)
        c.inputs, c.formula = inputs, f
        self.recompute(c)
        return c

    def visit(self, name, done, order, path):
        for c in self.cells:
            if name in c.inputs:
                if c.name in path:
                    return path + [c.name]
                if c.name not in done:
                    cycle = self.visit(c.name, done, order, path + [c.name])
                    if cycle:
                        return cycle
        done.append(name)
        order.append(name)
        return []

    def recalc(self, name):
        done, order = [], []
        cycle = self.visit(name, done, order, [name])
        if cycle:
            self.find(name).undo_redefine()
            self.events.emit("cycle", cycle)
            return cycle
        names = []
        for n in reversed(order):
            c = self.find(n)
            if c.inputs:
                self.recompute(c)
                names.append(f"{c.name}={fmt(c.value)}")
        self.events.emit("recalculated", names)
        return names

    def show(self):
        return "  ".join(f"{c.name}={fmt(c.value)}" for c in self.cells)


events = Events()
sheet = Sheet(events)
audit = []

def record(d):
    """d is the cell, the method's arguments, then its result."""
    if len(d) == 3:
        audit.append(f"{d[0].name} set to {fmt(d[1])}")
    else:
        audit.append(f"{d[0].name} given a formula over {', '.join(d[1])}")


events.when("changed", record)
events.when("changed", lambda d: sheet.recalc(d[0].name))
events.when("recalculated", lambda names: print("  recalculated: " + ", ".join(names)))
events.when("cycle", lambda path: print("  refused, a cycle: " + " -> ".join(path)))

net = sheet.cell("net", Fraction(10))
vat = sheet.formula_cell("vat", ["net"], lambda v: v[0] / 5)
gross = sheet.formula_cell("gross", ["net", "vat"], lambda v: v[0] + v[1])
share = sheet.formula_cell("share", ["gross"], lambda v: v[0] / 3)

print("== the sheet ==")
print(sheet.show())

print("== net set to 125/12 ==")
net.set(Fraction(125, 12))
print(sheet.show())

print("== VAT changed to a sixth ==")
vat.redefine(["net"], lambda v: v[0] / 6)
print(sheet.show())

print("== net redefined from share: a cycle ==")
net.redefine(["share"], lambda v: v[0] * 2)
print(sheet.show())

print("== net set to 20: the refused formula is gone, so this recalculates ==")
net.set(Fraction(20))
print(sheet.show())

print("== the audit trail, every edit asked for ==")
print("\n".join(audit))

Graduate Attributes

Directly developed

  • Critical Thinker: Readers compare two implementations of the same problem to evaluate where each language places its design effort.
  • Subject Specialist: Readers examine how different programming paradigms are combined to solve specific computational problems.

Modelled on this page

  • Digitally Fluent: Code outputs are verified against expected results across different operating systems and build types.
  • Reflective: The limitations of standard library tools are identified and addressed by building custom solutions.
  • Confident Communicator: Technical concepts are explained through concrete examples that contrast two distinct approaches.

University of Reading Graduate Attributes framework.