@tdjsnelling/nock
v1.1.0
Published
A Nock interpreter
Readme
nock
A small Nock interpreter written in TypeScript. Use it either:
- as an interactive REPL, or
- as a module for evaluating Nock formulas from your own code.
Install
As a library
yarn add @tdjsnelling/nockTo try the REPL
git clone https://github.com/tdjsnelling/nock
yarn install
yarn build
yarn start:replWhat you can do in the REPL
- Paste/type a Nock expression in the bracketed, space-separated form.
- The REPL will parse it and evaluate it, printing the result.
Using as a module
The package entry point exports:
parse(input: string)to turn a string into a Nock cell (AST/noun structure)- the public types from
types - the interpreter functionality as default
Basic pattern
import Nock, { parse } from "nock";
const formula = parse("[42 0 1]");
const subject = formula[0]; // 42
const argument = formula[1]; // [0, 1]
const interpreter = new Nock();
const result = interpreter.nock(subject, argument);
console.log(result);Interpreter options
The interpreter constructor can take some extra options:
onHint: the function to call for the 'hint' opcode (11). Must return a noun (in which case this noun is the result of the evaluation), or null (in which case the hint acts as a side effect and normal evaluation of the operation proceeds).debug: enable debugging features.customDebug: by default, if debug is enabled,console.logis used to print helpful info during evaluation. This default behaviour can be replaced by providing acustomDebugfunction which receives the parameters that would ordinarily be logged to the console.
const interpreter = new Nock({
onHint: (tag: Noun, clue: Noun | null, subject: Noun, argument: Cell) => Noun | null,
debug: boolean,
customDebug: (data: DebugPayload) => void,
})Parsing only
If you only need parsing (e.g., to validate or transform input), you can do:
import { parse } from "nock";
const cell = parse("[[1 2] [3 4]]");
console.log(cell);Utility functions
import { checkAtom, checkCell } from "nock";
checkAtom(42); // Ok
checkAtom([0, 1]); // Exception
checkCell(42); // Exception
checkCell([0, 1]); // OkTypeScript types
The package ships some TypeScript types:
- Atom: a natural number
- Cell: an ordered pair of nouns
- Noun: atom or cell
import type { Atom, Cell, Noun } from "nock";