Last updated: 2026-11-21
PatLang Showcase: Several Paradigms in One Program
For new readers
Five programs that each combine three or four of PatLang's paradigms: a budget that checks its own sums, two game agents planning against each other, a build system that resumes after a crash, a calculator whose answers come with checked bounds, and a bank account taken from specification to tested code. Each sits beside the same program in Python. They build on the two-paradigm programs of the earlier pages, starting with the first four pairs.
The code shown is the file in the PatLang repository's showcase/ directory, and the output is what PatLang's test gates check it against, on the interpreter and as native builds for Windows and Linux. Each Python version runs in the same gates and prints the same lines, or a file of its own where the two differ by design.test gates: automated checks that validate program output
A household budget that checks its own sums
Objects, events, exact numbers and contracts. Each budget line is an object, and changing one raises an event that a handler uses to bring the totals up to date. Every method that moves money states as a contract what must hold afterwards: a transfer leaves the total unchanged, and a split divides an amount into parts that add back to it exactly. Amounts are exact fractions, so those contracts can use == and still hold after 100.00 has been split three ways into shares of 100/3. A wrong change stops at the method that made it, before any money moves. The last section tries a negative transfer inside a world, so only that world stops.contracts are pre/post conditions
# A household budget that checks its own sums.
#
# Paradigms: objects, events, exact numbers and contracts.
#
# Each budget line is an object; changing one raises an event, and a handler
# brings the totals up to date. Every method that moves money states, as a
# contract, what must be true afterwards: a transfer between lines leaves the
# total unchanged, a split divides an amount into parts that add back to it
# exactly. Because the amounts are exact fractions, those contracts can use ==
# and still hold after a third of 100.00 has been moved three ways. A wrong
# change stops at the method that made it, before anything is moved; the last
# part tries one inside a world, so only that world stops.
class Line {
field name = ""
field amount = 0
make a function called set takes self, v returns value raises line_changed
self.amount = v
return v
end
}
class Budget {
field lines = 0
field total = 0
field changes = 0
}
make a function called budget_new returns b
let b = new("Budget")
b.lines = vec_new()
return b
end
make a function called add_line takes b, name, amount returns l
let l = new("Line")
l.name = name
l.amount = amount
vec_push(b.lines, l)
b.total = b.total + amount
return l
end
make a function called line takes b, name returns l
let i = 0
while i < vec_len(b.lines) do
let l = vec_get(b.lines, i)
if l.name == name then
return l
end
let i = i + 1
end
assert false
return l
end
make a function called sum_lines takes b returns s
let s = 0
let i = 0
while i < vec_len(b.lines) do
let l = vec_get(b.lines, i)
let s = s + l.amount
let i = i + 1
end
return s
end
# Moves amount from one line to another; the total is unchanged, exactly.
make a function called transfer takes b, from, to, amount returns total
require amount > 0
let before = sum_lines(b)
line(b, from).set(line(b, from).amount - amount)
line(b, to).set(line(b, to).amount + amount)
let total = sum_lines(b)
ensure total == before
return total
end
# Moves a line's whole amount into others, in equal shares, exactly.
make a function called split takes b, from, into returns shares
require list_len(into) > 0
let amount = line(b, from).amount
let share = amount / list_len(into)
let before = sum_lines(b)
line(b, from).set(0)
let i = 0
while i < list_len(into) do
line(b, into[i]).set(line(b, into[i]).amount + share)
let i = i + 1
end
let shares = share
ensure (shares * list_len(into) == amount) and (sum_lines(b) == before)
return shares
end
make a function called money takes x returns text
let pennies = floor(x * 100 + 1 / 2)
let pad = ""
if pennies % 100 < 10 then
let pad = "0"
end
return "" + floor(pennies / 100) + "." + pad + (pennies % 100)
end
make a function called show takes b returns done
let i = 0
while i < vec_len(b.lines) do
let l = vec_get(b.lines, i)
print(" " + l.name + ": " + money(l.amount) + " (exactly " + l.amount + ")")
let i = i + 1
end
print(" total " + money(b.total) + ", after " + b.changes + " changes")
return true
end
let budget = budget_new()
# The handler keeps the running total; it sees every change to every line.
when line_changed do
budget.changes = budget.changes + 1
budget.total = sum_lines(budget)
end
add_line(budget, "rent", 900)
add_line(budget, "food", 300)
add_line(budget, "savings", 100)
add_line(budget, "fun", 0)
add_line(budget, "gifts", 0)
add_line(budget, "repairs", 0)
print("== the budget ==")
show(budget)
print("== 50 moved from food to fun ==")
transfer(budget, "food", "fun", 50)
show(budget)
print("== savings split three ways ==")
let share = split(budget, "savings", ["fun", "gifts", "repairs"])
print(" each share is " + share + ", and three shares are " + (share * 3))
show(budget)
# A transfer of a negative amount breaks transfer's require. Tried in a world
# of its own, the stop ends that world and the program carries on.
print("== a transfer of -20, tried in a world of its own ==")
let w = world_new()
let tried = world_call(w, || do
return transfer(budget, "fun", "food", 0 - 20)
end)
world_free(w)
print(" the world " + tried[0] + "; the total is still " + money(sum_lines(budget)) + ", after " + budget.changes + " changes")
Output:
Output (click to expand)
== the budget == rent: 900.00 (exactly 900) food: 300.00 (exactly 300) savings: 100.00 (exactly 100) fun: 0.00 (exactly 0) gifts: 0.00 (exactly 0) repairs: 0.00 (exactly 0) total 1300.00, after 0 changes == 50 moved from food to fun == rent: 900.00 (exactly 900) food: 250.00 (exactly 250) savings: 100.00 (exactly 100) fun: 50.00 (exactly 50) gifts: 0.00 (exactly 0) repairs: 0.00 (exactly 0) total 1300.00, after 2 changes == savings split three ways == each share is 100/3, and three shares are 100 rent: 900.00 (exactly 900) food: 250.00 (exactly 250) savings: 0.00 (exactly 0) fun: 83.33 (exactly 250/3) gifts: 33.33 (exactly 100/3) repairs: 33.33 (exactly 100/3) total 1300.00, after 6 changes == a transfer of -20, tried in a world of its own == the world stopped; the total is still 1300.00, after 6 changes
Exact money is fractions.Fraction, which Python does well. The change event becomes a list of callbacks the setter calls, and the contracts become asserts at the start and end of each function, which python -O removes. The refused transfer is an exception caught around it. Where the PatLang output says the world stopped, the Python output names the exception.
The Python version
"""The budget sheet of showcase/c1_budget_sheet.patlang, in Python.
Exact money is fractions.Fraction, which Python does well. The line's
change event becomes a list of callbacks the setter calls, and the contracts
become asserts at the start and end of each function, which python -O
removes. The refused transfer is an exception caught around it; PatLang runs
it in a world, so whatever the failing code had done (files, facts, output)
would go with it too.
Where the PatLang program says the world stopped, this one names the
exception; its expected output is showcase/compare/expected/c1_budget_sheet.txt.
"""
from fractions import Fraction
from math import floor
class Line:
def __init__(self, budget, name, amount):
self.budget, self.name, self.amount = budget, name, amount
def set(self, v):
self.amount = v
for f in self.budget.on_change:
f(self)
return v
class Budget:
def __init__(self):
self.lines, self.total, self.changes, self.on_change = [], 0, 0, []
def add_line(b, name, amount):
line = Line(b, name, Fraction(amount))
b.lines.append(line)
b.total += line.amount
return line
def line(b, name):
for l in b.lines:
if l.name == name:
return l
raise KeyError(name)
def sum_lines(b):
return sum((l.amount for l in b.lines), Fraction(0))
def transfer(b, frm, to, amount):
assert amount > 0
before = sum_lines(b)
line(b, frm).set(line(b, frm).amount - amount)
line(b, to).set(line(b, to).amount + amount)
total = sum_lines(b)
assert total == before
return total
def split(b, frm, into):
assert len(into) > 0
amount = line(b, frm).amount
share = amount / len(into)
before = sum_lines(b)
line(b, frm).set(0)
for name in into:
line(b, name).set(line(b, name).amount + share)
assert share * len(into) == amount and sum_lines(b) == before
return share
def show_num(x):
x = Fraction(x)
return str(x.numerator) if x.denominator == 1 else str(x)
def money(x):
pennies = floor(Fraction(x) * 100 + Fraction(1, 2))
return f"{pennies // 100}.{pennies % 100:02d}"
def show(b):
for l in b.lines:
print(f" {l.name}: {money(l.amount)} (exactly {show_num(l.amount)})")
print(f" total {money(b.total)}, after {b.changes} changes")
budget = Budget()
def on_change(_line):
budget.changes += 1
budget.total = sum_lines(budget)
budget.on_change.append(on_change)
for name, amount in [("rent", 900), ("food", 300), ("savings", 100), ("fun", 0), ("gifts", 0), ("repairs", 0)]:
add_line(budget, name, amount)
print("== the budget ==")
show(budget)
print("== 50 moved from food to fun ==")
transfer(budget, "food", "fun", 50)
show(budget)
print("== savings split three ways ==")
share = split(budget, "savings", ["fun", "gifts", "repairs"])
print(f" each share is {show_num(share)}, and three shares are {show_num(share * 3)}")
show(budget)
print("== a transfer of -20, tried in a world of its own ==")
try:
transfer(budget, "fun", "food", -20)
outcome = "finished"
except AssertionError:
outcome = "raised AssertionError"
print(f" the try {outcome}; the total is still {money(sum_lines(budget))}, after {budget.changes} changes")
Two agents after the same coins
Goal-oriented planning, fibres, events and worlds. A row of seven squares holds two coins, and each of two agents plans the cheapest way to get one. The agents are fibres: the game resumes each in turn, and each yields the one move it wants to make. Each plans in a world of its own, so one agent's planning facts and numbers stay out of the other's. When an agent takes a coin, the game raises an event. Ann's plan was aimed at the coin Bo has just taken, so she marks it stale, plans again for the far coin, and gets there.
# Two agents after the same coins.
#
# Paradigms: goal-oriented planning, fibres, events and worlds.
#
# A row of seven squares holds two coins. Each agent wants a coin and plans
# the cheapest way to get one. The agents are fibres: the game resumes each in
# turn, and each yields the one move it wants to make. Each agent plans in a
# world of its own, so its planning facts and numbers are its own; two agents
# planning at once cannot see or disturb each other's plans. When an agent
# takes a coin the game raises an event; the other agent's plan may be aimed
# at that coin, so it marks itself stale and plans again next turn.
class Game {
field coins = []
field log = 0
}
class Agent {
field name = ""
field pos = 0
field has_coin = 0
field stale = true
field plan = []
}
# The agent's plan from the game as it is now, made in a world of its own:
# the actions and numbers it plans with exist only there, and go with it.
make a function called plan_for takes agent, game returns steps
let pos = agent.pos
let coins = game.coins
let w = world_new()
let r = world_call(w, || do
fluent_set("pos", pos)
fluent_set("has_coin", 0)
action_add_numeric("right", [], [["pos", "<", 6]], [], [], [["pos", "+=", 1]], 1)
action_add_numeric("left", [], [["pos", ">", 0]], [], [], [["pos", "-=", 1]], 1)
let i = 0
while i < list_len(coins) do
action_add_numeric("take_at_" + coins[i], [], [["pos", "==", coins[i]]], [], [], [["has_coin", "=", 1]], 1)
let i = i + 1
end
return plan_numeric([], [["has_coin", "==", 1]])
end)
world_free(w)
# a world's call gives ["done", value], or says how it stopped
assert r[0] == "done"
let steps = r[1]
return steps
end
# An agent, as a fibre: plans when its plan is stale, then yields its next
# move. The first resume passes in [agent, game].
make a function called agent_loop takes start returns last
let agent = start[0]
let game = start[1]
while agent.has_coin == 0 do
if agent.stale then
agent.plan = plan_for(agent, game)
agent.stale = false
vec_push(game.log, agent.name + " plans: " + plan_labels(agent.plan))
end
let move = step_name(agent.plan[0])
agent.plan = list_drop_first(agent.plan)
fiber_yield(move)
end
while true do
fiber_yield("done")
end
return 0
end
make a function called list_drop_first takes items returns rest
let rest = []
let i = 1
while i < list_len(items) do
let rest = list_push(rest, items[i])
let i = i + 1
end
return rest
end
make a function called without takes items, x returns rest
let rest = []
let i = 0
while i < list_len(items) do
if items[i] != x then
let rest = list_push(rest, items[i])
end
let i = i + 1
end
return rest
end
# Carries out a move; a take of a coin still there raises coin_taken.
make a function called apply_move takes game, agent, move returns done
if move == "right" then
agent.pos = agent.pos + 1
elif move == "left" then
agent.pos = agent.pos - 1
elif move != "done" then
let at = agent.pos
if list_len(without(game.coins, at)) < list_len(game.coins) then
game.coins = without(game.coins, at)
agent.has_coin = 1
emit("coin_taken", [agent.name, at])
else
# the coin went before this agent got there: plan again
agent.stale = true
end
end
return true
end
let game = new("Game")
game.coins = [2, 5]
game.log = vec_new()
let ann = new("Agent")
ann.name = "ann"
ann.pos = 0
let bo = new("Agent")
bo.name = "bo"
bo.pos = 3
let agents = [ann, bo]
# Every agent still after a coin hears that one is gone, and plans again.
when coin_taken do
vec_push(game.log, event_data[0] + " takes the coin at " + event_data[1])
let k = 0
while k < list_len(agents) do
let other = agents[k]
if (other.name != event_data[0]) and (other.has_coin == 0) then
other.stale = true
end
let k = k + 1
end
end
let fibres = [fiber_new("agent_loop"), fiber_new("agent_loop")]
let turn = 0
while ((ann.has_coin == 0) or (bo.has_coin == 0)) and (turn < 20) do
let a = 0
while a < list_len(agents) do
let agent = agents[a]
if agent.has_coin == 0 then
let move = fiber_resume(fibres[a], [agent, game])
apply_move(game, agent, move)
vec_push(game.log, "turn " + (turn + 1) + ": " + agent.name + " " + move + ", now on " + agent.pos)
end
let a = a + 1
end
let turn = turn + 1
end
print(str_join(vec_to_list(game.log), chr(10)))
print("ann has a coin: " + (ann.has_coin == 1) + ", bo has a coin: " + (bo.has_coin == 1))
Output:
ann plans: [right, right, take_at_2] turn 1: ann right, now on 1 bo plans: [left, take_at_2] turn 1: bo left, now on 2 turn 2: ann right, now on 2 bo takes the coin at 2 turn 2: bo take_at_2, now on 2 ann plans: [right, right, right, take_at_5] turn 3: ann right, now on 3 turn 4: ann right, now on 4 turn 5: ann right, now on 5 ann takes the coin at 5 turn 6: ann take_at_5, now on 5 ann has a coin: true, bo has a coin: true
Python's generators make good agents: the game sends each one the state and it yields its next move, as the PatLang fibres do. The planner is again written by hand, as a cheapest-first search over position and whether a coin is held. Separate worlds have no counterpart in this version, because its search keeps all its state in local variables, while PatLang's planner keeps actions and fluents in stores that two agents would otherwise share.generators keep state in local vars, not stores
The Python version
"""The two coin-seeking agents of showcase/c2_game_agents.patlang, in Python.
Python's generators make good agents: the game sends each one the state and
it yields its next move, as the PatLang fibres do. Python has no planner in
its standard library, so the sketch writes a cheapest-first search over
(position, has a coin); the PatLang agents describe their moves as actions
with conditions, effects and costs and ask plan_numeric. Planning in a world
of its own needs no counterpart here, because the search keeps its state in
local variables; the PatLang planner's actions and fluents are stores, and
the world keeps one agent's out of the other's.
Prints the same lines as the PatLang program.
"""
import heapq
from itertools import count
def plan_for(pos, coins):
"""The cheapest moves from pos to holding a coin: each move costs 1."""
tie = count()
frontier = [(0, next(tie), pos, False, [])]
seen = set()
while frontier:
cost, _, p, has, steps = heapq.heappop(frontier)
if has:
return steps
if (p, has) in seen:
continue
seen.add((p, has))
moves = []
if p < 6:
moves.append(("right", p + 1, False))
if p > 0:
moves.append(("left", p - 1, False))
for c in coins:
if p == c:
moves.append((f"take_at_{c}", p, True))
for name, np, nhas in moves:
heapq.heappush(frontier, (cost + 1, next(tie), np, nhas, steps + [name]))
return []
class Agent:
def __init__(self, name, pos):
self.name, self.pos, self.has_coin, self.stale, self.plan = name, pos, False, True, []
def agent_loop(agent, game):
while not agent.has_coin:
if agent.stale:
agent.plan = plan_for(agent.pos, game["coins"])
agent.stale = False
game["log"].append(f"{agent.name} plans: [{', '.join(agent.plan)}]")
move = agent.plan.pop(0)
yield move
while True:
yield "done"
game = {"coins": [2, 5], "log": []}
ann, bo = Agent("ann", 0), Agent("bo", 3)
agents = [ann, bo]
def coin_taken(name, at):
game["log"].append(f"{name} takes the coin at {at}")
for other in agents:
if other.name != name and not other.has_coin:
other.stale = True
def apply_move(agent, move):
if move == "right":
agent.pos += 1
elif move == "left":
agent.pos -= 1
elif move != "done":
if agent.pos in game["coins"]:
game["coins"] = [c for c in game["coins"] if c != agent.pos]
agent.has_coin = True
coin_taken(agent.name, agent.pos)
else:
agent.stale = True
loops = [agent_loop(a, game) for a in agents]
turn = 0
while (not ann.has_coin or not bo.has_coin) and turn < 20:
for agent, loop in zip(agents, loops):
if not agent.has_coin:
move = next(loop)
apply_move(agent, move)
game["log"].append(f"turn {turn + 1}: {agent.name} {move}, now on {agent.pos}")
turn += 1
print("\n".join(game["log"]))
print(f"ann has a coin: {'true' if ann.has_coin else 'false'}, bo has a coin: {'true' if bo.has_coin else 'false'}")
A build system in a page
Logic programming, parallel functional code and a durable queue. Targets and their dependencies are facts, and a rule says what a target needs, directly or not. The builder works in waves: every target whose dependencies are built is ready, and the ready ones are built at once by parallel_map. Each finished target goes into a queue on disk as soon as it is built, so an interrupted build resumes where it stopped and rebuilds nothing it already has. "Building" here means computing a checksum of a target's name and its dependencies' checksums, so a change anywhere shows in everything above it.the daemon keeps state alive
# A build system in a page.
#
# Paradigms: logic programming, parallel functional code and a durable queue.
#
# Targets and what each depends on are facts; a rule says what a target
# needs, directly or not. The builder works in waves: every target whose
# dependencies are built is ready, and the ready ones are built at the same
# time by parallel_map. Each finished target is recorded in a queue on disk
# as soon as it is built, so a build that is interrupted resumes where it
# stopped and rebuilds nothing it already has.
#
# "Building" a target here is computing a checksum of its name and its
# dependencies' checksums, so a change anywhere shows in everything above it.
#
# Given --page PATH, the program also draws the dependency graph as a web
# page, from the same facts the builder uses: a column for each wave, its
# targets grouped, a curve from each dependency to what needs it, and each
# target titled with its checksum (lib/dom.patlang).
include "../self_hosting/lib/queue.patlang"
include "../self_hosting/lib/dom.patlang"
rule depends(app, ui).
rule depends(app, core).
rule depends(app, net).
rule depends(ui, core).
rule depends(net, core).
rule depends(core, util).
rule depends(tests, app).
rule depends(tests, util).
rule target(util).
rule target(core).
rule target(net).
rule target(ui).
rule target(app).
rule target(tests).
rule needs(T, D) :- depends(T, D).
rule needs(T, D) :- depends(T, X), needs(X, D).
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 direct_deps takes t returns deps
let sols = solve("depends", [t, logic_var("D")])
let deps = []
let i = 0
while i < list_len(sols) do
let deps = list_push(deps, sols[i][1])
let i = i + 1
end
return deps
end
# The targets not yet built whose dependencies all are.
make a function called ready takes built returns out
let all = solve("target", [logic_var("T")])
let out = []
let i = 0
while i < list_len(all) do
let t = all[i][0]
if not has(built, t) then
let deps = direct_deps(t)
let ok = true
let k = 0
while k < list_len(deps) do
if not has(built, deps[k]) then
let ok = false
end
let k = k + 1
end
if ok then
let out = list_push(out, t)
end
end
let i = i + 1
end
return out
end
# A checksum of a text: the sum of its bytes times their positions, mod 9973.
make a function called checksum takes text returns c
let b = bytes_from_str(text)
let c = 0
let i = 0
while i < bytes_len(b) do
let c = (c + b[i] * (i + 1)) % 9973
let i = i + 1
end
return c
end
# One build job: [target, its dependencies' checksums] -> [target, checksum].
make a function called build_one takes job returns result
return [job[0], checksum(job[0] + ":" + str_join(job[1], ","))]
end
let topic = "showcase_c3_built"
queue_remove_topic(topic)
# The build, in waves, starting from the [target, checksum] pairs already
# built. stop_after_waves < 0 builds everything; otherwise the builder stops
# after that many waves, as an interrupted build would.
make a function called build takes topic, sums, stop_after_waves returns built
let built = []
let i = 0
while i < list_len(sums) do
let built = list_push(built, sums[i][0])
let i = i + 1
end
let wave = 0
while true do
let todo = ready(built)
if list_len(todo) == 0 then
if wave == 0 then
print(" nothing to build: every target is up to date")
end
return built
end
if wave == stop_after_waves then
print(" interrupted before building " + str_join(todo, ", "))
return built
end
let jobs = []
let j = 0
while j < list_len(todo) do
let deps = direct_deps(todo[j])
let dep_sums = []
let d = 0
while d < list_len(deps) do
let k = 0
while k < list_len(sums) do
if sums[k][0] == deps[d] then
let dep_sums = list_push(dep_sums, "" + sums[k][1])
end
let k = k + 1
end
let d = d + 1
end
let jobs = list_push(jobs, [todo[j], dep_sums])
let j = j + 1
end
let results = parallel_map(jobs, "build_one")
let r = 0
while r < list_len(results) do
queue_publish(topic, results[r][0] + " " + results[r][1])
let sums = list_push(sums, results[r])
let built = list_push(built, results[r][0])
let r = r + 1
end
print(" wave " + (wave + 1) + ": built " + str_join(todo, ", "))
let wave = wave + 1
end
return built
end
# What earlier runs recorded: each message is "target checksum", read back as
# [target, checksum]. (q_read gives each message as [id, status, payload].)
make a function called sums_on_disk takes topic returns sums
let rows = q_read(topic)
let sums = []
let i = 0
while i < list_len(rows) do
let text = rows[i][2]
let sp = 0
while text[sp] != " " do
let sp = sp + 1
end
let sums = list_push(sums, [substr(text, 0, sp), to_num(substr(text, sp + 1, text.length - sp - 1))])
let i = i + 1
end
return sums
end
# ---- the page ----
# The waves a build from nothing makes: each the targets ready once the
# earlier waves are built.
make a function called waves_of returns waves
let waves = []
let built = []
let todo = ready(built)
while list_len(todo) > 0 do
let waves = list_push(waves, todo)
let t = 0
while t < list_len(todo) do
let built = list_push(built, todo[t])
let t = t + 1
end
let todo = ready(built)
end
return waves
end
# [wave index, row in it] of target t.
make a function called place_of takes waves, t returns at
let k = 0
while k < list_len(waves) do
let i = 0
while i < list_len(waves[k]) do
if waves[k][i] == t then
return [k, i]
end
let i = i + 1
end
let k = k + 1
end
assert false
return [0, 0]
end
make a function called sum_of takes sums, t returns c
let i = 0
while i < list_len(sums) do
if sums[i][0] == t then
return sums[i][1]
end
let i = i + 1
end
return 0
end
# A column of 120 per wave, rows of 50 from 80. Each edge is a curve that
# arcs up 30 for each wave it passes over, so it clears the boxes between.
make a function called graph_page takes sums returns page
let waves = waves_of()
let page = dom_page("The build's dependencies")
let body = dom_body(page)
dom_set_text(dom_append(body, dom_element("h1")), "The build's dependencies")
let rows = 0
let k = 0
while k < list_len(waves) do
let rows = max(rows, list_len(waves[k]))
let k = k + 1
end
let svg = dom_append(body, dom_element("svg"))
dom_set_attr(svg, "width", "" + (20 + 120 * list_len(waves)))
dom_set_attr(svg, "height", "" + (80 + 50 * rows))
let count = 0
let k = 0
while k < list_len(waves) do
let i = 0
while i < list_len(waves[k]) do
let t = waves[k][i]
let count = count + 1
let deps = direct_deps(t)
let d = 0
while d < list_len(deps) do
let from = place_of(waves, deps[d])
let x1 = 20 + 120 * from[0] + 80
let y1 = 80 + 50 * from[1] + 15
let x2 = 20 + 120 * k
let y2 = 80 + 50 * i + 15
let bend = 0 - 30 * (k - from[0] - 1)
let path = dom_append(svg, dom_element("path"))
dom_set_attr(path, "d", "M " + x1 + " " + y1 + " C " + (x1 + 40) + " " + (y1 + bend) + " " + (x2 - 40) + " " + (y2 + bend) + " " + x2 + " " + y2)
dom_set_attr(path, "fill", "none")
dom_set_attr(path, "stroke", "#94a3b8")
let d = d + 1
end
let i = i + 1
end
let k = k + 1
end
let k = 0
while k < list_len(waves) do
let x = 20 + 120 * k
let g = dom_append(svg, dom_element("g"))
dom_set_attr(g, "id", "wave-" + (k + 1))
let label = dom_set_text(dom_append(g, dom_element("text")), "wave " + (k + 1))
dom_set_attr(label, "x", "" + (x + 40))
dom_set_attr(label, "y", "40")
dom_set_attr(label, "text-anchor", "middle")
let i = 0
while i < list_len(waves[k]) do
let t = waves[k][i]
let y = 80 + 50 * i
let box = dom_append(g, dom_element("rect"))
dom_set_attr(box, "x", "" + x)
dom_set_attr(box, "y", "" + y)
dom_set_attr(box, "width", "80")
dom_set_attr(box, "height", "30")
dom_set_attr(box, "rx", "4")
dom_set_attr(box, "fill", "#e0e7ff")
dom_set_attr(box, "stroke", "#6366f1")
dom_set_text(dom_append(box, dom_element("title")), t + ", checksum " + sum_of(sums, t))
let name = dom_set_text(dom_append(g, dom_element("text")), t)
dom_set_attr(name, "x", "" + (x + 40))
dom_set_attr(name, "y", "" + (y + 20))
dom_set_attr(name, "text-anchor", "middle")
let i = i + 1
end
let k = k + 1
end
dom_set_text(dom_append(body, dom_element("p")), "" + count + " targets in " + list_len(waves) + " waves")
return page
end
print("== what app needs, directly or not ==")
let needs = solve("needs", ["app", logic_var("D")])
let names = []
let i = 0
while i < list_len(needs) do
if not has(names, needs[i][1]) then
let names = list_push(names, needs[i][1])
end
let i = i + 1
end
print(" " + str_join(names, ", "))
print("== a build, interrupted after two waves ==")
build(topic, sums_on_disk(topic), 2)
print(" recorded on disk: " + list_len(sums_on_disk(topic)) + " targets")
print("== the build run again: it starts from what is on disk ==")
build(topic, sums_on_disk(topic), 0 - 1)
let all = sums_on_disk(topic)
print(" recorded on disk: " + list_len(all) + " targets")
print(" checksums: " + all)
print("== and once more, with nothing left to do ==")
build(topic, sums_on_disk(topic), 0 - 1)
queue_remove_topic(topic)
let args = argv()
if (list_len(args) == 2) and (args[0] == "--page") then
write_file(args[1], dom_document_html(graph_page(all)))
end
Output:
== what app needs, directly or not == ui, core, net, util == a build, interrupted after two waves == wave 1: built util wave 2: built core interrupted before building net, ui recorded on disk: 2 targets == the build run again: it starts from what is on disk == wave 1: built net, ui wave 2: built app wave 3: built tests recorded on disk: 6 targets checksums: [[util, 1386], [core, 2942], [net, 2248], [ui, 1648], [app, 9125], [tests, 7150]] == and once more, with nothing left to do == nothing to build: every target is up to date
With --page PATH the program draws its dependency graph, from the same facts the builder reads: a column for each wave, a curve from each dependency to the target that needs it, and each target titled with its checksum.
The page it writes:
Python writes the dependencies as a dict and "needs, directly or not" as a recursive generator, as briefly as the PatLang rules. The rules also answer the reverse question (what needs util?) as they stand, where Python would need another function. The waves run on a process pool, since threads would not run the checksums in parallel, and the record of finished targets is a file of lines, appended and flushed after each one, which is the usual substitute for a durable queue.
The Python version
"""The build system of showcase/c3_build_system.patlang, in Python.
The dependencies are a dict, and "needs, directly or not" is a recursive
generator, which Python writes as briefly as the two rules the PatLang
program has; a query the other way ("what needs util?") would be another
function, where the rules answer it as they stand. The waves run on a
process pool (threads would not run the checksums in parallel). The record
of what is built is a file of lines, appended and flushed after each target,
which the next run reads back: Python has no durable queue in its standard
library, and this is the usual substitute.
Prints the same lines as the PatLang program.
"""
import os
import tempfile
from concurrent.futures import ProcessPoolExecutor
DEPENDS = {"app": ["ui", "core", "net"], "ui": ["core"], "net": ["core"], "core": ["util"], "tests": ["app", "util"]}
TARGETS = ["util", "core", "net", "ui", "app", "tests"]
RECORD = os.path.join(tempfile.gettempdir(), "showcase_c3_built.txt")
def needs(t):
"""What t needs, in the order the PatLang rules give it: direct first."""
yield from DEPENDS.get(t, [])
for x in DEPENDS.get(t, []):
yield from needs(x)
def ready(built):
return [t for t in TARGETS if t not in built and all(d in built for d in DEPENDS.get(t, []))]
def checksum(text):
c = 0
for i, byte in enumerate(text.encode(), start=1):
c = (c + byte * i) % 9973
return c
def build_one(job):
target, dep_sums = job
return target, checksum(target + ":" + ",".join(dep_sums))
def sums_on_disk():
if not os.path.exists(RECORD):
return []
with open(RECORD) as f:
return [(t, int(c)) for t, c in (line.split() for line in f)]
def build(pool, sums, stop_after_waves):
built = [t for t, _ in sums]
wave = 0
while True:
todo = ready(built)
if not todo:
if wave == 0:
print(" nothing to build: every target is up to date")
return built
if wave == stop_after_waves:
print(" interrupted before building " + ", ".join(todo))
return built
jobs = [(t, [str(c) for d in DEPENDS.get(t, []) for n, c in sums if n == d]) for t in todo]
for target, c in pool.map(build_one, jobs):
with open(RECORD, "a") as f:
f.write(f"{target} {c}\n")
f.flush()
os.fsync(f.fileno())
sums.append((target, c))
built.append(target)
print(f" wave {wave + 1}: built " + ", ".join(todo))
wave += 1
if __name__ == "__main__":
if os.path.exists(RECORD):
os.remove(RECORD)
names = []
for d in needs("app"):
if d not in names:
names.append(d)
print("== what app needs, directly or not ==")
print(" " + ", ".join(names))
with ProcessPoolExecutor() as pool:
print("== a build, interrupted after two waves ==")
build(pool, sums_on_disk(), 2)
print(f" recorded on disk: {len(sums_on_disk())} targets")
print("== the build run again: it starts from what is on disk ==")
build(pool, sums_on_disk(), -1)
everything = sums_on_disk()
print(f" recorded on disk: {len(everything)} targets")
print(" checksums: [" + ", ".join(f"[{t}, {c}]" for t, c in everything) + "]")
print("== and once more, with nothing left to do ==")
build(pool, sums_on_disk(), -1)
os.remove(RECORD)
Formulas over measured values, with checked bounds
Syntax definitions, exact numbers and intervals, operator methods and contracts. Measurements are written as a lab notebook writes them, mass = 1250/1000 +- 5/1000 kg, in a notation defined at the top of the file. Each becomes a Measured value holding its nominal figure exactly and the interval it is known to lie in. Measured defines +, -, * and / as methods, so a formula such as kinetic energy is ordinary arithmetic that carries both along. Each operator's contract checks that the nominal result lies inside the result's interval, so every figure printed comes with bounds that have been checked.
# Formulas over measured values, with answers that come with proof.
#
# Paradigms: syntax definitions, exact numbers and intervals, operator
# methods, and contracts.
#
# Measurements are written as a lab notebook writes them, "mass = 1250/1000
# +- 5/1000 kg", in a notation defined at the top of the file. Each one
# becomes a Measured value holding its nominal figure, exactly, and the
# interval it is known to lie in. Measured defines + - * and / as methods, so
# a formula is written as ordinary arithmetic and carries both through. Each
# operator's contract checks that the nominal result lies inside the result's
# interval, so every figure printed comes with bounds that have been checked,
# not estimated.
syntax LabNotebook {
trigger: Keyword("measurements");
tokens {
Name(n) = regex("[a-z_]+", n);
Num(v) = regex("[0-9]+", v);
Slash = "/";
Equals = "=";
PlusMinus = "+-";
}
rule Reading {
let name = expect Name;
expect Equals;
let top = expect Num;
expect Slash;
let bottom = expect Num;
expect PlusMinus;
let tol_top = expect Num;
expect Slash;
let tol_bottom = expect Num;
let unit = expect Name;
return rule_add("reading", [name, to_num(top) / to_num(bottom), to_num(tol_top) / to_num(tol_bottom), unit], []);
}
}
class Measured {
field nominal = 0
field range = 0
make a function called + takes self, other returns sum
return measured_from(self.nominal + nominal_of(other), self.range + range_of(other))
end
make a function called - takes self, other returns diff
return measured_from(self.nominal - nominal_of(other), self.range - range_of(other))
end
make a function called * takes self, other returns product
return measured_from(self.nominal * nominal_of(other), self.range * range_of(other))
end
# Intervals have no division of their own: dividing by [c,d] is multiplying
# by [1/d, 1/c], which is an interval only when [c,d] leaves out zero.
make a function called / takes self, other returns quotient
let d = range_of(other)
require (interval_lo(d) > 0) or (interval_hi(d) < 0)
let reciprocal = interval_make(1 / interval_hi(d), 1 / interval_lo(d))
return measured_from(self.nominal / nominal_of(other), self.range * reciprocal)
end
}
# A plain number in a formula is exact: its range is itself.
make a function called nominal_of takes x returns n
if type_of(x) == "Measured" then
return x.nominal
end
return x
end
make a function called range_of takes x returns r
if type_of(x) == "Measured" then
return x.range
end
return interval_make(x, x)
end
# The contract every result keeps: its nominal figure lies in its range.
make a function called measured_from takes nominal, range returns m
require (interval_lo(range) <= nominal) and (nominal <= interval_hi(range))
let m = new("Measured")
m.nominal = nominal
m.range = range
ensure (interval_lo(m.range) <= m.nominal) and (m.nominal <= interval_hi(m.range))
return m
end
make a function called reading takes name returns m
let sols = solve("reading", [name, logic_var("V"), logic_var("T"), logic_var("U")])
assert list_len(sols) == 1
let v = sols[0][1]
let t = sols[0][2]
return measured_from(v, interval_make(v - t, v + t))
end
# x to four places: rounded to the nearest (way 0), down (way -1) or up (way
# 1). A bound is printed rounded outwards, so the printed range still holds.
make a function called decimal takes x, way returns text
let n = floor(x * 10000 + 1 / 2)
if way < 0 then
let n = floor(x * 10000)
elif way > 0 then
let n = 0 - floor(0 - x * 10000)
end
let frac = "" + (n % 10000)
let pad = ""
if frac.length == 1 then
let pad = "000"
elif frac.length == 2 then
let pad = "00"
elif frac.length == 3 then
let pad = "0"
end
return "" + floor(n / 10000) + "." + pad + frac
end
make a function called report takes label, m returns done
print(label + ": " + decimal(m.nominal, 0) + ", certainly between " + decimal(interval_lo(m.range), -1) + " and " + decimal(interval_hi(m.range), 1))
return true
end
measurements {
mass = 1250/1000 +- 5/1000 kg
speed = 340/100 +- 2/100 m_per_s
drop = 2/1 +- 1/100 m
g = 981/100 +- 1/100 m_per_s_squared
}
let mass = reading("mass")
let speed = reading("speed")
let drop = reading("drop")
let g = reading("g")
print("== readings ==")
report("mass (kg)", mass)
report("speed (m/s)", speed)
print("== formulas ==")
let kinetic = mass * speed * speed / 2
report("kinetic energy, m v^2 / 2 (J)", kinetic)
let potential = mass * g * drop
report("potential energy, m g h (J)", potential)
let total = kinetic + potential
report("their sum (J)", total)
print("the kinetic energy exactly: " + kinetic.nominal)
Output:
== readings == mass (kg): 1.2500, certainly between 1.2450 and 1.2550 speed (m/s): 3.4000, certainly between 3.3800 and 3.4200 == formulas == kinetic energy, m v^2 / 2 (J): 7.2250, certainly between 7.1116 and 7.3395 potential energy, m g h (J): 24.5250, certainly between 24.2799 and 24.7715 their sum (J): 31.7500, certainly between 31.3916 and 32.1110 the kinetic energy exactly: 289/40
Python's operator overloading suits this well: its Measured defines __add__, __sub__, __mul__ and __truediv__, and the formulas read as arithmetic in both. Python supplies no interval, so the sketch carries a small one over fractions.Fraction, and reads the notebook notation with a regular expression at run time. The contract on each operation is an assert.contracts catch bugs at runtime, not compile time
The Python version
"""The measured-value calculator of showcase/c4_proven_calculator.patlang, in Python.
Python's operator overloading suits this well: Measured defines __add__,
__sub__, __mul__ and __truediv__, as the PatLang class defines + - * and /,
and a formula reads as arithmetic in both. What Python lacks is the interval
itself, so the sketch carries the small one it needs over fractions.Fraction,
and the notebook notation is read with a regular expression at run time
where PatLang defines it as syntax. The contract that each nominal figure
lies inside its interval is an assert in each operation.
Prints the same lines as the PatLang program.
"""
import re
from fractions import Fraction
from math import floor
NOTEBOOK = """
mass = 1250/1000 +- 5/1000 kg
speed = 340/100 +- 2/100 m_per_s
drop = 2/1 +- 1/100 m
g = 981/100 +- 1/100 m_per_s_squared
"""
class Interval:
def __init__(self, lo, hi):
assert lo <= hi
self.lo, self.hi = lo, hi
def __add__(self, o):
return Interval(self.lo + o.lo, self.hi + o.hi)
def __sub__(self, o):
return Interval(self.lo - o.hi, self.hi - o.lo)
def __mul__(self, o):
ends = [self.lo * o.lo, self.lo * o.hi, self.hi * o.lo, self.hi * o.hi]
return Interval(min(ends), max(ends))
def nominal_of(x):
return x.nominal if isinstance(x, Measured) else Fraction(x)
def range_of(x):
return x.range if isinstance(x, Measured) else Interval(Fraction(x), Fraction(x))
class Measured:
def __init__(self, nominal, rng):
assert rng.lo <= nominal <= rng.hi
self.nominal, self.range = nominal, rng
def __add__(self, o):
return Measured(self.nominal + nominal_of(o), self.range + range_of(o))
def __sub__(self, o):
return Measured(self.nominal - nominal_of(o), self.range - range_of(o))
def __mul__(self, o):
return Measured(self.nominal * nominal_of(o), self.range * range_of(o))
def __truediv__(self, o):
d = range_of(o)
assert d.lo > 0 or d.hi < 0
return Measured(self.nominal / nominal_of(o), self.range * Interval(1 / d.hi, 1 / d.lo))
READINGS = {}
for m in re.finditer(r"(\w+) = (\d+)/(\d+) \+- (\d+)/(\d+) (\w+)", NOTEBOOK):
v, t = Fraction(int(m[2]), int(m[3])), Fraction(int(m[4]), int(m[5]))
READINGS[m[1]] = Measured(v, Interval(v - t, v + t))
def decimal(x, way):
"""x to four places: to the nearest (0), down (-1) or up (1)."""
if way < 0:
n = floor(x * 10000)
elif way > 0:
n = -floor(-x * 10000)
else:
n = floor(x * 10000 + Fraction(1, 2))
return f"{n // 10000}.{n % 10000:04d}"
def report(label, m):
print(f"{label}: {decimal(m.nominal, 0)}, certainly between {decimal(m.range.lo, -1)} and {decimal(m.range.hi, 1)}")
mass, speed, drop, g = (READINGS[k] for k in ("mass", "speed", "drop", "g"))
print("== readings ==")
report("mass (kg)", mass)
report("speed (m/s)", speed)
print("== formulas ==")
kinetic = mass * speed * speed / 2
report("kinetic energy, m v^2 / 2 (J)", kinetic)
potential = mass * g * drop
report("potential energy, m g h (J)", potential)
report("their sum (J)", kinetic + potential)
print(f"the kinetic energy exactly: {kinetic.nominal}")
A bank account, specified, explored, implemented and tested
Declared schemas, contracts, exact numbers, objects and executable specifications. The account is first written as a schema: its state, what must always be true of it, and its operations with their preconditions and effects. An explorer visits every state the operations can reach and checks the invariants in each. The first version of the schema forgets that a withdrawal needs the money to be there, and the explorer finds the shortest sequence that breaks the invariant: one withdrawal from an empty account. The corrected schema explores clean, across 11 states and 30 transitions. The account is then written as a class whose methods carry the corrected schema's preconditions and effects as require and ensure clauses on exact amounts, and a Gherkin feature exercises it.contracts catch errors early before code runs
# A bank account, specified, explored, implemented and tested.
#
# Paradigms: declared schemas, contracts, exact numbers, objects and
# executable specifications.
#
# The account is first specified as a schema: its state, what must always be
# true of it, and its operations with their preconditions and effects. The
# explorer visits every state the operations can reach and checks the
# invariants in each. A first version of the schema forgets that a withdrawal
# needs the money to be there; the explorer finds the shortest sequence of
# operations that breaks the invariant. The corrected schema explores clean.
#
# The account is then written as a class whose methods carry the corrected
# schema's preconditions and effects as require and ensure clauses, on exact
# amounts, and a Gherkin feature exercises it.
include "../self_hosting/lib/includes.patlang"
include "../self_hosting/lib/gherkin.patlang"
include "../self_hosting/lib/zs_explore.patlang"
make a function called schema_text takes checked returns text
let guard = ""
if checked then
let guard = " require balance >= amount" + chr(10)
end
return str_join([
"schema Account",
"state balance",
"init balance = 0",
"domain amount = set_of(20, 50)",
"invariant balance >= 0",
"invariant balance <= 100",
"",
"operation Deposit(amount)",
" require balance + amount <= 100",
" ensure balance' == balance + amount",
"end",
"",
"operation Withdraw(amount)",
guard + " ensure balance' == balance - amount",
"end",
""
], chr(10))
end
make a function called explore takes ctx, label, checked returns verdict
let loaded = zs_load(ctx, schema_text(checked))
assert loaded[0] == "ok"
let r = zs_explore(ctx, "Account", 10000)
print("== " + label + " ==")
let lines = zs_format_exploration(r)
let i = 0
while i < list_len(lines) do
print(" " + lines[i])
let i = i + 1
end
return r[0]
end
# ---- the implementation, carrying the schema's clauses ----
class Account {
field balance = 0
make a function called deposit takes self, amount returns balance
require (amount > 0) and (self.balance + amount <= 100)
let before = self.balance
self.balance = self.balance + amount
let balance = self.balance
ensure (balance == before + amount) and (balance >= 0) and (balance <= 100)
return balance
end
make a function called withdraw takes self, amount returns balance
require (amount > 0) and (self.balance >= amount)
let before = self.balance
self.balance = self.balance - amount
let balance = self.balance
ensure (balance == before - amount) and (balance >= 0)
return balance
end
}
make a function called st_account takes ctx returns ok
let a = new("Account")
ctx_set(ctx, "account", a)
return true
end
make a function called st_deposit takes ctx returns ok
let a = ctx_get(ctx, "account")
a.deposit(to_num(step_arg(ctx, "n")))
return true
end
make a function called st_withdraw takes ctx returns ok
let a = ctx_get(ctx, "account")
a.withdraw(to_num(step_arg(ctx, "n")))
return true
end
make a function called st_balance takes ctx returns ok
let a = ctx_get(ctx, "account")
return expect(ctx, "the balance", "" + a.balance, step_arg(ctx, "n"))
end
let ctx = ctx_new()
explore(ctx, "the first schema: withdrawal unchecked", false)
explore(ctx, "the corrected schema", true)
print("== the implementation, against its feature ==")
let feature = str_join([
"Feature: an account",
"",
" Scenario: deposits add up exactly",
" Given a new account",
" When 20 is deposited",
" And 101/4 is deposited",
" Then the balance is 181/4",
"",
" Scenario: a withdrawal takes away exactly what was asked",
" Given a new account",
" When 50 is deposited",
" And 1/3 is withdrawn",
" Then the balance is 149/3"
], chr(10))
step(ctx, "a new account", "st_account")
step(ctx, "{n} is deposited", "st_deposit")
step(ctx, "{n} is withdrawn", "st_withdraw")
step(ctx, "the balance is {n}", "st_balance")
run_feature(ctx, feature)
ctx_report(ctx)
Output:
== the first schema: withdrawal unchecked ==
Withdraw reaches a state that breaks an invariant: balance >= 0
step 1: Withdraw with {20}
== the corrected schema ==
Explored every reachable state: 11 states, 30 transitions. No invariant or postcondition was violated.
== the implementation, against its feature ==
Feature: an account
Scenario: deposits add up exactly
ok: the balance
Scenario: a withdrawal takes away exactly what was asked
ok: the balance
tests: 2 passed, 0 failed
ALL TESTS PASSED
Python has no state-space explorer in its standard distribution, so the sketch writes one for this schema: a breadth-first search over balances, with the operations as functions and the invariants checked after each step. Outside Python, TLA+ with its model checker and Alloy do this kind of exploration, each in a language of its own. The class and its feature then follow as in the PatLang program, with asserts for the contracts and a step matcher written with re.
The Python version
"""The specified bank account of showcase/c5_specified_bank.patlang, in Python.
The PatLang program states the account as a schema (state, invariants,
operations with preconditions and effects) and hands it to an explorer in
its library, which visits every reachable state. Python has no such library
in its standard distribution, so the sketch writes the explorer for this one
schema: a breadth-first search over balances, the operations as functions,
the invariants checked after each step. Tools for this exist outside Python:
TLA+ and its model checker, or Alloy, each with a language of its own. The
implementation and its Gherkin feature then follow as in the PatLang program,
with asserts for its require and ensure clauses and a step matcher written
with re.
Prints the same lines as the PatLang program.
"""
import re
from collections import deque
from fractions import Fraction
AMOUNTS = [20, 50]
INVARIANTS = [("balance >= 0", lambda b: b >= 0), ("balance <= 100", lambda b: b <= 100)]
def operations(checked):
"""(name, enabled(balance, amount), effect(balance, amount))"""
return [
("Deposit", lambda b, a: b + a <= 100, lambda b, a: b + a),
("Withdraw", (lambda b, a: b >= a) if checked else (lambda b, a: True), lambda b, a: b - a),
]
def explore(label, checked):
print(f"== {label} ==")
seen, transitions = {0: []}, 0
todo = deque([0])
while todo:
b = todo.popleft()
for name, enabled, effect in operations(checked):
for a in AMOUNTS:
if not enabled(b, a):
continue
transitions += 1
nb = effect(b, a)
path = seen[b] + [(name, a)]
for text, holds in INVARIANTS:
if not holds(nb):
print(f" {name} reaches a state that breaks an invariant: {text}")
for i, (op, arg) in enumerate(path, start=1):
print(f" step {i}: {op} with {{{arg}}}")
return
if nb not in seen:
seen[nb] = path
todo.append(nb)
print(f" Explored every reachable state: {len(seen)} states, {transitions} transitions. No invariant or postcondition was violated.")
class Account:
def __init__(self):
self.balance = Fraction(0)
def deposit(self, amount):
assert amount > 0 and self.balance + amount <= 100
before = self.balance
self.balance += amount
assert self.balance == before + amount and 0 <= self.balance <= 100
return self.balance
def withdraw(self, amount):
assert amount > 0 and self.balance >= amount
before = self.balance
self.balance -= amount
assert self.balance == before - amount and self.balance >= 0
return self.balance
def show(x):
return str(x.numerator) if x.denominator == 1 else str(x)
explore("the first schema: withdrawal unchecked", False)
explore("the corrected schema", True)
print("== the implementation, against its feature ==")
FEATURE = """Feature: an account
Scenario: deposits add up exactly
Given a new account
When 20 is deposited
And 101/4 is deposited
Then the balance is 181/4
Scenario: a withdrawal takes away exactly what was asked
Given a new account
When 50 is deposited
And 1/3 is withdrawn
Then the balance is 149/3"""
passed = failed = 0
ctx = {}
def st_balance(want):
global passed, failed
got = show(ctx["account"].balance)
if got == want:
passed += 1
print(" ok: the balance")
else:
failed += 1
print(f" FAIL: the balance (got {got}, want {want})")
STEPS = [
(r"a new account", lambda: ctx.__setitem__("account", Account())),
(r"(\S+) is deposited", lambda n: ctx["account"].deposit(Fraction(n))),
(r"(\S+) is withdrawn", lambda n: ctx["account"].withdraw(Fraction(n))),
(r"the balance is (\S+)", st_balance),
]
for line in FEATURE.splitlines():
line = line.strip()
if line.startswith(("Feature:", "Scenario:")):
print(line)
continue
words = line.split(" ", 1)
if len(words) == 2 and words[0] in ("Given", "When", "Then", "And"):
for pattern, f in STEPS:
m = re.fullmatch(pattern, words[1])
if m:
f(*m.groups())
break
print(f"tests: {passed} passed, {failed} failed")
print("ALL TESTS PASSED" if failed == 0 else "TESTS FAILED")
Graduate Attributes
Directly developed
- Critical Thinker: Readers compare how PatLang and Python handle the same problem to judge the trade-offs between language features.
- Digitally Fluent: Readers examine code implementations across different paradigms to understand how digital tools structure logic and data.
Modelled on this page
- Subject Specialist: Complex programming concepts like contracts, fibres and state-space exploration are explained through concrete, working code examples.
- Reflective: The limitations of each language implementation are stated explicitly alongside the advantages of the primary tool.
- Confident Communicator: Technical distinctions between paradigms are clarified using precise terminology and parallel comparisons.
University of Reading Graduate Attributes framework.