3 Second Edition
| (require typed/miniKanren/amb/trs2) | package: ambKanren |
This module implements the language of the second edition of The Reasoned Schemer (Friedman, Byrd, Kiselyov, and Hemann, MIT Press, 2018) on top of amb, without streams.
3.1 Implementation Basis
The interface (run, defrel, fresh, conde, conda, condu, project) and the definitions of walk, unify, ifte, once, and reification follow the official code of the second edition. What changes is the representation of goals:
| second edition |
| typed/miniKanren/amb/trs2 | |
goal |
|
| ||
|
| a choice made by amb | ||
|
| a local search: (g2 (amb-local (g1 s))) | ||
suspension |
|
| amb-pause: one logical pause |
The second edition suspends every relation call. Here defrel calls amb-pause instead. When current-amb-merger is amb-interleave, that pause lets the other side of a binary choice run. The examples below select this merger explicitly:
3.1.1 Order of Answers
With amb-interleave and the default shuffler, all 285 examples of the book that the tests cover give the same answers in the same order.
This depends on conj2. Like append-map-inf, it searches g1 locally and continues with g2 from each answer, so the runs of g2 are interleaved in the order of the answers of g1, with the pauses of g1 in between. Plain function composition, (g2 (g1 s)), runs g2 inside the choices of g1, so the runs are interleaved following the shape of those choices. When both versions completely enumerate a pure search without pruning, they produce the same answers in possibly different orders. With composition, (conj2 (disj2 a b) g) is (disj2 (conj2 a g) (conj2 b g)), order included, whereas the book’s bind keeps the answers of (disj2 a b) together; two examples, in Chapter 8 and Chapter 9, return their answers in another order. The price of the local search is one more search per conjunction.
The other mergers give other orders: amb-alternate also passes the turn at answers, and amb-level runs in rounds of pauses. With them, a bounded run need not return the same answers as the book. The migration report of the package records the examples that differ.
3.2 Types
type
type
type
type
type
3.3 Running Programs
syntax
(run* q goal ...)
3.4 Goals and Relations
syntax
(fresh (x ...) goal ...)
syntax
(conde [goal ...+] ...)
syntax
(conda [goal ...+] ...+)
syntax
(condu [goal ...+] ...+)
syntax
(project (x ...) goal ...)
syntax
(disj goal ...)
syntax
(conj goal ...)
procedure
g1 : Goal g2 : Goal
procedure
g1 : Goal g2 : Goal
3.5 Substitutions and Unification
value
procedure
v : Term s : Substitution
procedure
v : Term s : Substitution
procedure
x : Var v : Term s : Substitution
procedure
(ext-s x v s) → Substitution
x : Var v : Term s : Substitution
procedure
(unify u v s) → Substitution
u : Term v : Term s : Substitution
procedure
(reify-name n) → Symbol
n : Index
procedure
(reify-s v r) → Substitution
v : Term r : Substitution
procedure
(reify v) → (→ Substitution Term)
v : Term