@yaks/logic 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/term.ts ADDED
@@ -0,0 +1,250 @@
1
+ // Terms, and unifying them. A term is any value: a variable, a scalar, or a
2
+ // list or object holding terms. An env is a plain object from a variable's name
3
+ // to its value, and it is never changed in place: binding a variable answers a
4
+ // copy (`set`). Unifying two terms answers the env that makes them equal, or
5
+ // null when none does. A `splat` in a list stands for a run of its items, so
6
+ // `[x, splat(y)]` is a list's head and its tail.
7
+ import { beget, tap, typeOf } from '@yaks/fp'
8
+ import type { Env } from './goal.ts'
9
+
10
+ /** A name for a slot in an env: a variable, or a relation keeping its facts. */
11
+ export type Slot = { isVar: boolean; toString(): string }
12
+
13
+ /** Any value: a variable, a scalar, or a list or object holding terms. */
14
+ // deno-lint-ignore no-explicit-any -- a term is whatever it is bound to
15
+ export type Term = any
16
+
17
+ /**
18
+ * A logic variable. A named one is one variable wherever the name is written,
19
+ * so `lvar('x') === lvar('x')`; a fresh one has a name of its own.
20
+ */
21
+ export class Var {
22
+ name: string
23
+ constructor(name: string) {
24
+ this.name = name
25
+ }
26
+ get isVar(): boolean {
27
+ return true
28
+ }
29
+ toString(): string {
30
+ return this.name
31
+ }
32
+ /** The variable named for this one's part `name`: `x.var('a')` is `x.a`. */
33
+ var(name: string): Var {
34
+ return lvar(`${this}.${name}`)
35
+ }
36
+ }
37
+
38
+ let named = new Map<string, Var>()
39
+ let fresh = 0
40
+
41
+ /// lvar() ~> Var
42
+ /// lvar('x') -> lvar('x')
43
+ /// lvar() == lvar() -> false
44
+ /** The variable `name`, or a fresh one. */
45
+ export let lvar = (name?: string): Var =>
46
+ name == null
47
+ ? new Var(`~.${fresh++}`)
48
+ : named.get(name) ?? tap((v: Var) => named.set(name, v))(new Var(name))
49
+
50
+ /// nvars(3) ~> [Var, Var, Var]
51
+ /** `length` fresh variables. */
52
+ export let nvars = (length: number): Var[] =>
53
+ Array.from({ length }, () => lvar())
54
+
55
+ /// lvars.x -> lvar('x')
56
+ /** Every named variable, by its name: `let { a, b } = lvars`. */
57
+ export let lvars: Record<string, Var> = new Proxy({}, {
58
+ get: (_, name) => typeof name == 'string' ? lvar(name) : undefined,
59
+ })
60
+
61
+ export let x: Var = lvar('x')
62
+ export let y: Var = lvar('y')
63
+ export let z: Var = lvar('z')
64
+
65
+ /// isVar(x) -> true
66
+ /// isVar(1) -> false
67
+ /** Whether a term names a slot in an env: a variable, or a relation's facts. */
68
+ export let isVar = (x: Term): boolean => Boolean(x?.isVar)
69
+
70
+ /** `_` unifies with any value, and never binds. */
71
+ export let _: Var = lvar('_')
72
+
73
+ /** `...value` inside a list: a run of the list's items. */
74
+ export class Splat {
75
+ value: Term
76
+ constructor(value: Term) {
77
+ this.value = value
78
+ }
79
+ }
80
+
81
+ /// splat([1]) ~> Splat
82
+ /** `...value` inside a list pattern or literal. */
83
+ export let splat = (value: Term): Splat => new Splat(value)
84
+
85
+ /// isSplat(splat(x)) -> true
86
+ /// isSplat(x) -> false
87
+ export let isSplat = (x: Term): x is Splat => x instanceof Splat
88
+
89
+ /// get(x)({ x: 1 }) -> 1
90
+ /// get(y, 0)({}) -> 0
91
+ /** What `key` is bound to, or `def`. */
92
+ export let get = (key: Term, def?: Term) => (env: Env): Term => env[key] ?? def
93
+
94
+ /// set(x, 1)({}) -> { x: 1 }
95
+ /// set(_, 1)({}) -> {}
96
+ /** The env with `key` bound to `value`; `_` binds nothing. */
97
+ export let set = (key: Term, value: Term) => (env: Env): Env =>
98
+ key === _ || value === _ ? env : beget(env, (e) => e[key] = value)
99
+
100
+ /// update(x, (n = 0) => n + 1)({ x: 1 }) -> { x: 2 }
101
+ /** The env with `key` bound to `fn` of what it was. */
102
+ export let update = (key: Term, fn: (v: Term) => Term) => (env: Env): Env =>
103
+ set(key, fn(env[key]))(env)
104
+
105
+ /// walk(x, { x: 1 }) -> 1
106
+ /// walk(x, { x: y, y: 1 }) -> 1
107
+ /// walk(x, {}) -> x
108
+ /** A variable's value, followed through the variables it is bound to. */
109
+ export let walk = (x: Term, env: Env): Term => {
110
+ if (!isVar(x)) return x
111
+ let val = env[x]
112
+ return val === undefined ? x : walk(val, env)
113
+ }
114
+
115
+ /// walkAll({ x: 1, y: 2 }, [x, y]) -> [1, 2]
116
+ export let walkAll = (env: Env, xs: Term[]): Term[] =>
117
+ xs.map((x) => walk(x, env))
118
+
119
+ let plain = (x: Term): boolean =>
120
+ typeOf(x) == 'object' &&
121
+ [Object.prototype, null].includes(Object.getPrototypeOf(x))
122
+
123
+ /// deepwalk(x, { x: y, y: 1 }) -> 1
124
+ /// deepwalk([x, y], { x: y, y: 1 }) -> [1, 1]
125
+ /// deepwalk([x, splat([y])], { x: y, y: 1 }) -> [1, 1]
126
+ /// deepwalk({ a: [x] }, { x: 1 }) -> { a: [1] }
127
+ /**
128
+ * A term with every variable inside it walked: a splat whose value is a list
129
+ * becomes its items. A plain object is walked into; any other object, a
130
+ * response or a date, is a value of its own.
131
+ */
132
+ export let deepwalk = (x: Term, env: Env): Term => {
133
+ if (isSplat(x)) return splat(deepwalk(x.value, env))
134
+ if (plain(x)) {
135
+ return Object.fromEntries(
136
+ Object.entries(x).map(([k, v]) => [k, deepwalk(v, env)]),
137
+ )
138
+ }
139
+ if (!Array.isArray(x)) {
140
+ let y = walk(x, env)
141
+ return x == y ? y : deepwalk(y, env)
142
+ }
143
+ return x.flatMap((v) => {
144
+ if (!isSplat(v)) return [deepwalk(v, env)]
145
+ let tail = deepwalk(v.value, env)
146
+ return Array.isArray(tail) ? tail : [splat(tail)]
147
+ })
148
+ }
149
+
150
+ /// occurs(x, [x], {}) -> true
151
+ /// occurs(x, { x }, {}) -> true
152
+ /// occurs(x, [y], {}) -> false
153
+ /** Whether `v` occurs inside `x`: binding `v` to `x` would never end. */
154
+ export let occurs = (v: Var, x: Term, env: Env): boolean => {
155
+ x = walk(x, env)
156
+ if (x === v) return true
157
+ if (Array.isArray(x)) return x.some((item) => occurs(v, item, env))
158
+ if (x && typeof x == 'object') {
159
+ return Object.values(x).some((item) => occurs(v, item, env))
160
+ }
161
+ return false
162
+ }
163
+
164
+ /// unify(x, 1, {}) -> { x: 1 }
165
+ /// unify([x, 2], [1, y], {}) -> { x: 1, y: 2 }
166
+ /// unify({ a: x }, { b: 1 }, {}) -> null
167
+ /// unify(1, 2, {}) -> null
168
+ /**
169
+ * The env that makes `a` and `b` equal, or null. A variable binds unless it
170
+ * occurs in what it would be bound to; lists unify item by item, a splat
171
+ * taking whatever run of items fits, and objects key by key.
172
+ */
173
+ export let unify = (a: Term, b: Term, env: Env): Env | null => {
174
+ a = walk(a, env)
175
+ b = walk(b, env)
176
+
177
+ if (a === b) return env
178
+ if (isVar(a)) return occurs(a, b, env) ? null : set(a, b)(env)
179
+ if (isVar(b)) return occurs(b, a, env) ? null : set(b, a)(env)
180
+ if (typeOf(a) != typeOf(b)) return null
181
+ if (Array.isArray(a)) return unifyArrays(a, b, env)
182
+ if (typeOf(a) == 'object') return unifyObjects(a, b, env)
183
+ return null
184
+ }
185
+
186
+ // Each pair unified in turn: the first that fails fails them all.
187
+ let pairs = (ps: Term[][], env: Env | null): Env | null =>
188
+ ps.reduce((e, [a, b]) => e && unify(a, b, e), env)
189
+
190
+ /** Two lists unified item by item; a splat on either side takes a run. */
191
+ export let unifyArrays = (a: Term[], b: Term[], env: Env): Env | null =>
192
+ a.some(isSplat) || b.some(isSplat)
193
+ ? splats(a, b, env)
194
+ : a.length == b.length
195
+ ? pairs(a.map((x, i) => [x, b[i]]), env)
196
+ : null
197
+
198
+ let splats = (a: Term[], b: Term[], env: Env, i = 0, j = 0): Env | null => {
199
+ if (i >= a.length && j >= b.length) return env
200
+ if (isSplat(a[i])) {
201
+ return stretch(
202
+ a[i].value,
203
+ i + 1,
204
+ b,
205
+ j,
206
+ env,
207
+ (i, j, env) => splats(a, b, env, i, j),
208
+ )
209
+ }
210
+ if (isSplat(b[j])) {
211
+ return stretch(
212
+ b[j].value,
213
+ j + 1,
214
+ a,
215
+ i,
216
+ env,
217
+ (j, i, env) => splats(a, b, env, i, j),
218
+ )
219
+ }
220
+ if (i >= a.length || j >= b.length) return null
221
+ let next = unify(a[i], b[j], env)
222
+ return next && splats(a, b, next, i + 1, j + 1)
223
+ }
224
+
225
+ // A splat unified with each run of the other side's items from `from` on,
226
+ // shortest first, until the rest of the lists unify too.
227
+ let stretch = (
228
+ value: Term,
229
+ after: number,
230
+ other: Term[],
231
+ from: number,
232
+ env: Env,
233
+ rest: (after: number, to: number, env: Env) => Env | null,
234
+ ): Env | null => {
235
+ for (let to = from; to <= other.length; to++) {
236
+ let next = unify(value, other.slice(from, to), env)
237
+ let done = next && rest(after, to, next)
238
+ if (done) return done
239
+ }
240
+ return null
241
+ }
242
+
243
+ /** Two objects unified key by key: each has the keys the other has. */
244
+ export let unifyObjects = (a: Env, b: Env, env: Env): Env | null => {
245
+ let keys = Object.keys(a)
246
+ return keys.length == Object.keys(b).length &&
247
+ keys.every((k) => Object.hasOwn(b, k))
248
+ ? pairs(keys.map((k) => [a[k], b[k]]), env)
249
+ : null
250
+ }