logic_js
v0.1.1
Published
TypeScript implementation of a modified version of miniKanren, a logic programming language embedded in JavaScript
Maintainers
Readme
logic.js
A TypeScript implementation of a modified version of miniKanren, a logic programming language embedded in JavaScript.
Logic programs describe relations instead of functions: you state what must
be true and let run search for the values that make it true. The library is
small (a few hundred lines), typed, and ships both ESM and CommonJS builds.
Install
npm install logic_jsWorks in Node.js and in the browser. TypeScript types are bundled — no
@types package needed.
Quick start
import { lvar, run, and, or, eq } from 'logic_js'
const x = lvar('x') // a logic variable with id 'x'
run(1, [x], eq(x, 1))
// => [{ x: 1 }]
run(1, [x], (y = lvar()) => and(eq(y, 1), eq(x, y)))
// => [{ x: 1 }]
run([x], or(eq(x, 1), eq(x, 2)))
// => [{ x: 1 }, { x: 2 }]
run([x], or(1, eq(x, 1), eq(x, 2)))
// => [{ x: 1 }] (a leading number limits that `or`)CommonJS works too:
const { lvar, run, eq } = require('logic_js')In the browser, load the IIFE build and use the logic global.
From a CDN — jsDelivr resolves logic_js to the minified build via the
jsdelivr field in package.json:
<script src="https://cdn.jsdelivr.net/npm/logic_js/dist/logic.global.min.js"></script>
<script>
const { lvar, run, eq } = logic
const x = lvar('x')
console.log(run(1, [x], eq(x, 'hello world'))) // [{ x: 'hello world' }]
</script>Pin an exact version for production, and use npm/ with an explicit path so a
future package change can't move the file:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/logic.global.min.js"></script>The same file is available from unpkg:
<script src="https://unpkg.com/logic_js/dist/logic.global.min.js"></script>Locally, after npm install (or npm run build in this repo):
<script src="node_modules/logic_js/dist/logic.global.min.js"></script>Both dist/logic.global.js (readable, with source map) and
dist/logic.global.min.js (minified) define the same logic global.
How run works
run has two forms:
run(num, vars, goal) // at most `num` solutions
run(vars, goal) // every solutionvarsis a logic variable or an array of them.goalis a goal, or a function returning a goal. Use a function when the goal needs fresh logic variables.- Each solution is an object keyed by the queried variables' ids:
[{ x: 1 }]. Unbound variables keep theirLVarvalue.
Core relations
Facts and rules
import { lvar, run, and, facts } from 'logic_js'
// Steve is Bob's parent, Steve is Henry's parent, Henry is Alice's parent
const parent = facts(
['Steve', 'Bob'],
['Steve', 'Henry'],
['Henry', 'Alice'],
)
const x = lvar('x')
run(1, [x], parent(x, 'Alice')) // => [{ x: 'Henry' }]
run(2, [x], parent('Steve', x)) // => [{ x: 'Bob' }, { x: 'Henry' }]
// A rule is just a function that builds a goal.
const grandparent = (a: unknown, b: unknown) => {
const z = lvar()
return and(parent(a, z), parent(z, b))
}
run(1, [x], grandparent(x, 'Alice')) // => [{ x: 'Steve' }]Lists
import { lvar, run, conso, firsto, resto, emptyo, membero, appendo } from 'logic_js'
const x = lvar('x')
const y = lvar('y')
run([x], membero(x, [1, 2, 3]))
// => [{ x: 1 }, { x: 2 }, { x: 3 }]
run([x, y], conso(x, y, [1, 2, 3]))
// => [{ x: 1, y: [2, 3] }]
run([x], firsto(x, [1, 2, 3])) // => [{ x: 1 }]
run([x], resto(x, [1, 2, 3])) // => [{ x: [2, 3] }]
run([x], emptyo(x)) // => [{ x: [] }]
run([x, y], appendo(x, y, [1, 2]))
// => [{ x: [], y: [1, 2] }, { x: [1], y: [2] }, { x: [1, 2], y: [] }]conso, firsto and resto build improper lists internally when the tail
is unknown, so relations like appendo work in every direction.
Arithmetic and comparison
import { lvar, run, add, sub, mul, div, lt, le, gt, ge } from 'logic_js'
const x = lvar('x')
run(1, [x], add(2, x, 5)) // => [{ x: 3 }]
run(1, [x], sub(15, x, 12)) // => [{ x: 3 }]
run(1, [x], mul(2, x, 7)) // => [{ x: 3.5 }]
run(1, [x], div(12, x, 3)) // => [{ x: 4 }]Arithmetic relations need at least two of their three arguments to be numbers, so at most one may be an unbound variable.
Comparison goals succeed only when both sides have resolved to numbers:
run([x], and(eq(x, 2), gt(x, 1))) // => [{ x: 2 }]
run([x], and(eq(x, 2), lt(x, 1))) // => []Type constraints
numbero, stringo and arrayo succeed when their argument resolves to that
type. Combine them with other goals to filter solutions:
run([x], and(eq(x, 'a'), stringo(x))) // => [{ x: 'a' }]Control
import { lvar, run, and, or, eq, succeed, fail, anyo } from 'logic_js'
const x = lvar('x')
run([x], and(eq(x, 1), succeed())) // => [{ x: 1 }]
run([x], and(eq(x, 1), fail())) // => []
run([x], or(eq(x, 1), and(eq(x, 2), fail()), eq(x, 3)))
// => [{ x: 1 }, { x: 3 }]
run(4, [x], anyo(or(eq(x, 1), eq(x, 2))))
// => [{ x: 1 }, { x: 2 }, { x: 1 }, { x: 2 }]API
| Export | Description |
| --- | --- |
| lvar(id?) | Create a logic variable. |
| run(num, vars, goal) / run(vars, goal) | Run a goal and collect solutions. |
| eq(x, y) | Unify two terms. |
| and(...goals) | Conjunction. |
| or(...goals) / or(count, ...goals) | Disjunction, optionally capped. |
| succeed() / fail() | Goals that always succeed or fail. |
| facts(...rows) | Build a relation from ground rows. |
| conso(first, rest, out) | out is [first, ...rest]. |
| firsto(first, out) | first is the head of out. |
| resto(rest, out) | rest is the tail of out. |
| emptyo(x) | x is []. |
| membero(x, arr) | x is an element of arr. |
| appendo(a, b, out) | out is a followed by b. |
| anyo(goal) | Repeat goal forever. |
| add(a, b, c) | a + b === c. |
| sub(a, b, c) | a - b === c. |
| mul(a, b, c) | a * b === c. |
| div(a, b, c) | a / b === c. |
| lt, le, gt, ge | Numeric comparisons. |
| numbero(x), stringo(x), arrayo(x) | Type constraints. |
| LVar, isLVar(x) | Logic variable class and guard. |
| ImmutableMap | Persistent substitution map. |
| walk, deepwalk, unify | Low-level unification helpers. |
| DOT, isArray | Improper-list marker and array guard. |
Types
The public types are exported for building your own goals:
import type { Goal, GoalClause, QueryResult, Term, Substitution } from 'logic_js'A Goal is a generator that consumes a Substitution and yields extended
substitutions (or null on failure). GoalClause is a Goal or a
zero-argument function returning one.
Development
npm install
npm run typecheck # type-check src and tests
npm test # run the Vitest suite
npm run build # emit dist/ (ESM + CJS + IIFE + minified IIFE + .d.ts)
npm run verify # smoke-test all published entry pointstests/test.html is a manual browser smoke test for the IIFE build.
Releasing
Releases are published by GitHub Actions on a version tag, so no local publish step is needed.
Bump the version (this updates
package.jsonandpackage-lock.json):npm version minor --no-git-tag-version # or major / patchCommit the bump, open a PR, and merge it once CI is green.
Tag the merge commit on
masterand push the tag:git tag v0.2.0 git push origin v0.2.0
The Release workflow then verifies that the tag matches package.json,
re-runs typecheck, tests, build and verify, publishes to npm with a
provenance attestation, and creates a GitHub release.
Prerequisite: an NPM_TOKEN repository secret containing an npm automation
token with publish rights for logic_js.
Publishing makes the minified bundle available on jsDelivr at:
https://cdn.jsdelivr.net/npm/logic_js@<version>/dist/logic.global.min.jsMigrating from 0.0.x
The package is now written in TypeScript and ships its own types.
lib/logic.jswas replaced by thedist/build. Browser users should loaddist/logic.global.jsordist/logic.global.min.js; Node users shouldrequire('logic_js')orimport ... from 'logic_js'instead of deep-importing a file.All 0.0.x exports still exist, and both named and default imports work:
import logic, { lvar, run, eq } from 'logic_js' const { lvar: lvar2 } = logicArithmetic is stricter.
add,sub,mulanddivnow require numeric operands. 0.0.x used bare JS operators for the ground case, soadd('1', 2, '12')oradd(true, 1, 2)used to succeed; they now fail.eq(x, undefined)now keepsxbound. 0.0.x treatedundefinedas "unbound" and silently dropped the binding.runwith anumof0,NaNorundefinedreturns[](unchanged), and a negativenumcollects every solution (unchanged).consothrows a descriptiveTypeErrorifrestis neither an array nor a logic variable, instead of a bare "not iterable" error.Results are returned on a null-prototype object, so an lvar id of
__proto__is preserved as a real key.
