forked from codewars/lambda-calculus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda-calculus.js
More file actions
442 lines (417 loc) · 16.9 KB
/
lambda-calculus.js
File metadata and controls
442 lines (417 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/*
Lambda Calculus evaluator supporting:
- unlimited recursion
- call by need
- fast (ish?) evaluation
- shortform syntax
And additional features:
- debugging aids
- predefined encodings
- purity modes
Written by
JohanWiltink - https://github.com/JohanWiltink
Kacarott - https://github.com/Kacarott
*/
// Default options
const config = { verbosity: "Calm" // Calm | Concise | Loquacious | Verbose
, purity: "PureLC" // Let | LetRec | PureLC
, numEncoding: "None" // None | Church | Scott | BinaryScott
, enforceBinaryScottInvariant: true // Boolean
};
export function configure(cfg={}) { return Object.assign(config,cfg); }
function union(left, right) {
const r = new Set(left);
for ( const name of right ) r.add(name);
return r;
}
class V {
constructor(name) { this.name = name; }
free() { return new Set([ this.name ]); }
toString() { return this.name.toString(); }
}
class L {
constructor(name, body) {
this.name = name;
this.body = body;
}
free() {
const r = this.body?.free?.() || new Set ;
r.delete(this.name);
return r;
}
toString() {
return this.body instanceof L
? `\\ ${this.name}${this.body.toString().slice(1)}`
: `\\ ${this.name} . ${this.body.toString()}`;
}
}
class A {
constructor(left, right) {
this.left = left;
this.right = right;
}
free() { return union( this.left?.free?.() || [] , this.right?.free?.() || [] ); }
toString() {
const left = this.left instanceof L ? `(${this.left})` : this.left ;
const right = this.right instanceof V ? this.right : `(${this.right})` ;
return `${left} ${right}`;
}
}
class Env extends Map {
// use inherited set, get for copying references
// insert and retrieve values with setThunk and getValue
// encoding of value is a Generator Object that yields value forever - this is opaque
setThunk(i,val) {
this.set(i, function*() {
// console.warn(`expensively calculating ${ i }`);
const result = (yield val) ?? val; // If val is not A or V, then it need not be evaluated
while ( true ) yield result;
} () );
return this;
}
// Second argument provides an interface for storing the evaluated term inside
// the generator, for future accesses.
getValue(i, result) {
// console.warn(`inexpensively fetching ${ i }`);
return this.get(i).next(result).value;
}
}
// Term and Env pair, used internally to keep track of current computation in eval
class Tuple {
constructor(term,env) { Object.assign(this,{term,env}); }
valueOf() { return toInt(this.term); }
toString() { return this.term.toString(); }
}
// Used to insert an external (JS) value into evaluation manually ( avoiding implicit number conversion )
export function Primitive(v) { return new Tuple(new V( "<primitive>" ), new Env([[ "<primitive>" , function*() { while ( true ) yield v; } () ]])); }
const primitives = new Env;
primitives.setThunk( "trace", new Tuple( Primitive( function(v) { console.info(String(v.term)); return v; } ), new Env ) );
const Y = new L("f",new A(new L("x",new A(new V("f"),new A(new V("x"),new V("x")))),new L("x",new A(new V("f"),new A(new V("x"),new V("x"))))));
export function fromInt(n) {
if ( config.numEncoding === "Church" )
if ( n >= 0 )
return new L("s", new L("z", Array(n).fill().reduce( s => new A(new V("s"), s), new V("z")) ));
else {
if ( config.verbosity >= "Concise" ) console.error(`fromInt.Church: negative number ${ n }`);
throw new RangeError;
}
else if ( config.numEncoding === "Scott" ) // data Int = Zero | Succ Int
if ( n >= 0 )
return new Array(n).fill().reduce( v => new L('_', new L('f', new A(new V('f'), v))), new L('z', new L('_', new V('z'))) );
else {
if ( config.verbosity >= "Concise" ) console.error(`fromInt.Scott: negative number ${ n }`);
throw new RangeError;
}
else if ( config.numEncoding === "BinaryScott" ) // data Int = End | Even Int | Odd Int // LittleEndian, padding ( trailing ) 0 bits are out of spec - behaviour is undefined
if ( n >= 0 ) {
const zero = new L('z', new L('_', new L('_', new V('z'))));
return n ? n.toString(2).split("").reduce( (z,bit) => new L('_', new L('f', new L('t', new A(new V( bit==='0' ? 'f' : 't' ), z)))), zero ) : zero ;
} else {
if ( config.verbosity >= "Concise" ) console.error(`fromInt.BinaryScott: negative number ${ n }`);
throw new RangeError;
}
else if ( config.numEncoding === "None" ) {
if ( config.verbosity >= "Concise" ) console.error(`fromInt.None: number ${ n }`);
throw new EvalError;
} else
return config.numEncoding.fromInt(n); // Custom encoding
}
const isPadded = n => n (false) ( z => z (true) ( () => isPadded(z) ) ( () => isPadded(z) ) ) (isPadded) ; // check invariant for BinaryScott number
export function toInt(term) {
try {
if ( config.numEncoding === "Church" ) {
const succ = x => x+1 ;
const result = term ( succ ) ;
return result ( result === succ ? 0 : Primitive(0) );
} else if ( config.numEncoding === "Scott" ) {
let result = 0, evaluating = true;
while ( evaluating )
term ( () => evaluating = false ) ( n => () => { term = n; result++ } ) ();
return result;
} else if ( config.numEncoding === "BinaryScott" ) {
const throwOnPadding = config.enforceBinaryScottInvariant && isPadded(term);
let result = 0, bit = 1, evaluating = true;
while ( evaluating )
term ( () => evaluating = false ) ( n => () => { term = n; bit *= 2 } ) ( n => () => { term = n; result += bit; bit *= 2 } ) ();
if ( throwOnPadding ) {
if ( config.verbosity >= "Concise" ) console.error(`toInt: Binary Scott number ${ result } has zero-padding`);
throw new TypeError(`toInt: Binary Scott number violates invariant`);
}
return result;
} else if ( config.numEncoding === "None" )
return term;
else
return config.numEncoding.toInt(term); // Custom encoding
} catch (e) {
if ( ! e.message.startsWith("toInt:") && config.verbosity >= "Concise" )
console.error(`toInt: ${ term } is not a number in numEncoding ${ config.numEncoding }`);
throw e;
}
}
// parse :: String -> Env { String => Term }
export function parse(code) {
function parseTerm(env,code) {
function wrap(name,term) {
const FV = term?.free?.() || new Set ; FV.delete("()");
if ( config.purity === "Let" )
return Array.from(FV).reduce( (tm,nm) => {
if ( env.has(nm) ) {
if ( config.verbosity >= "Verbose" ) console.debug(` using ${ nm } = ${ env.getValue(nm) }`);
tm.env.set( nm, env.get(nm) );
return tm;
} else {
if ( config.verbosity >= "Concise" ) console.error(`parse: while defining ${ name } = ${ term }`);
if ( nm === name )
throw new ReferenceError(`undefined free variable ${ nm }: direct recursive calls are not supported in Let mode`);
else
throw new ReferenceError(`undefined free variable ${ nm }`);
}
} , new Tuple( term, new Env ) );
else if ( config.purity==="LetRec" )
return Array.from(FV).reduce( (tm,nm) => {
if ( nm === name )
return tm;
else if ( env.has(nm) ) {
if ( config.verbosity >= "Verbose" ) console.debug(` using ${ nm } = ${ env.getValue(nm) }`);
tm.env.set( nm, env.get(nm) );
return tm;
} else {
if ( config.verbosity >= "Concise" ) console.error(`parse: while defining ${ name } = ${ term }`);
throw new ReferenceError(`undefined free variable ${ nm }`);
}
} , new Tuple( FV.has(name) ? new A(Y,new L(name,term)) : term , new Env ) );
else if ( config.purity==="PureLC" )
if ( FV.size ) {
if ( config.verbosity >= "Concise" ) console.error(`parse: while defining ${ name } = ${ term }`);
throw new EvalError(`unresolvable free variable(s) ${ Array.from(FV) }: all expressions must be closed in PureLC mode`);
} else
return new Tuple( term, new Env );
else
throw new RangeError(`config.purity: unknown setting "${ purity }"`);
}
const letters = /[a-z]/i;
const digits = /\d/;
const identifierChars = /[-'\w]/;
const whitespace = /\s/;
function error(i,msg) {
console.error(code);
console.error(' '.repeat(i) + '^');
console.error(msg + " at position " + i);
throw new SyntaxError(msg);
}
function sp(i) { while ( whitespace.test( code[i] || "" ) ) i++; return i; }
const expect = c => function(i) { return code[i]===c ? sp(i+1) : 0 ; } ;
function name(i) {
if ( code[i]==='_' ) {
while ( identifierChars.test( code[i] || "" ) ) i++;
if ( code[i]==='?' ) i++;
return [sp(i),"_"];
} else if ( letters.test( code[i] || "" ) ) {
let j = i+1;
while ( identifierChars.test( code[j] || "" ) ) j++;
if ( code[j]==='?' ) j++;
return [sp(j),code.slice(i,j)];
} else
return null;
}
function n(i) {
if ( digits.test(code[i]) ) {
let j = i+1;
while ( digits.test(code[j]) ) j++;
return [ sp(j), fromInt(Number(code.slice(i,j))), Number(code.slice(i,j)) ]; // return JS number in addition to LC number // negative uses this
} else
return null;
}
function v(i) {
const r = name(i);
if ( r ) {
const [j,termName] = r;
if ( termName==="_" ) {
const undef = new V("()");
undef.defName = name(0)[1];
return [j,undef];
} else
return [j,new V(termName)];
} else
return null;
}
function l(i) {
const j = expect('\\')(i);
if ( j ) {
let arg, args = [];
let k = j;
while ( arg = name(k) ) {
[k,arg] = arg;
args.push(arg);
}
if ( args.length ) {
const l = expect('.')(k) || error(k,"lambda: expected '.'") ;
const [m,body] = term(l) || error(l,"lambda: expected a lambda calculus term") ;
return [ m, args.reduceRight( (body,arg) => new L(arg,body) , body ) ];
} else
error(k,"lambda: expected at least one named argument");
} else
return null;
}
function a(i) {
let q, r = [];
let j = i;
while ( q = paren_d(term)(j) || l(j) || v(j) || n(j) || negative(n)(j) ) {
[j,q] = q;
r.push(q);
}
if ( r.length )
return [ j, r.reduce( (z,term) => new A(z,term) ) ];
else
return null;
}
const negative = number => function(i) {
const j = expect('-')(i);
if ( j ) {
const q = number(j);
if ( q ) {
const [k,,r] = q; // act on the JS number instead of the LC number
return [k,fromInt(-r)];
} else
error(j,"negative: expected a number literal")
} else
return null;
}
const paren_d = inner => function(i) {
const j = expect('(')(i);
if ( j ) {
const q = inner(j);
if ( q ) {
const [k,r] = q;
const l = expect(')')(k) || error(k,"paren_d: expected ')'") ;
return [l,r];
} else {
const k = expect(')')(j) || error(j,"paren_d: expected ')'") ;
const undefinedTerm = new V("()");
undefinedTerm.defName = name(0)[1];
return [k, undefinedTerm];
}
} else
return null;
} ;
const term = a;
function defn(i) {
const [j,nm] = name(i) || error(i,"defn: expected a name") ;
const k = expect('=')(j) || error(j,"defn: expected '='") ;
const [l,tm] = term(k) || error(k,"defn: expected a lambda calculus term") ;
return [l,[nm,tm]];
}
const [i,r] = defn(0);
if ( i===code.length ) {
const [name,term] = r;
if ( config.verbosity >= "Loquacious" )
console.debug(`compiled ${ name }${ config.verbosity >= "Verbose" ? ` = ${ term }` : "" }`);
return env.setThunk( name, wrap(name,term));
} else
error(i,"defn: incomplete parse");
}
return code.replace( /#.*$/gm, "" ) // ignore comments
.replace( /\n(?=\s)/g, "" ) // continue lines
.split( '\n' ) // split lines
.filter( term => /\S/.test(term) ) // skip empty lines
.reduce(parseTerm, new Env(primitives)); // parse lines
}
export function compile(code) {
if ( typeof code !== "string" || ! code ) throw new TypeError("missing code");
const env = parse(code);
const r = {};
for ( const [name] of env )
Object.defineProperty( r, name, { get() { return evalLC(new Tuple(new V(name), env)); }, enumerable: true } );
return r;
}
// Top level call, term :: Tuple
function evalLC(term) {
// builds function to return to user ( representing an abstraction awaiting input )
function awaitArg(term, env) {
// callback function which will evaluate term.body in an env with the input
function result(arg) {
let argEnv;
if ( arg?.term && arg?.env ) ({ term: arg, env: argEnv } = arg); // if callback is passed another callback, or a term
const termVal = new Tuple( typeof arg === 'number' ? fromInt(arg) : arg , new Env(argEnv) );
if ( term.name==="_" )
return runEval( new Tuple(term.body, new Env(env)) );
else
return runEval( new Tuple(term.body, new Env(env).setThunk(term.name, termVal)) );
}
return Object.assign( result, {term,env} );
}
// term :: Tuple
// isRight :: bool (indicating whether the term is left or right side of an Application)
// isEvaluated :: bool (indicating whether the current term should be stored in the Env)
// callstack :: [String] (History of var lookups, for better error messages)
function runEval({term,env}) { // stack: [[term, isRight, isEvaluated]], term: LC term, env = Env { name => term }
const callstack = [], stack = []; // Does not persist between requests for arguments
while ( ! ( term instanceof L ) || stack.length > 0 ) {
if ( term instanceof V )
if ( term.name==="()" )
{ printStackTrace("eval: evaluating undefined", term, callstack); throw new EvalError; }
else {
callstack.push(term.name);
const res = env.getValue(term.name);
if ( ! res.env )
term = res;
else {
if (res.term instanceof V || res.term instanceof A)
// Push a frame to the stack to indicate when the value should be stored back
stack.push( [new Tuple( term, env ), true, true ] );
({term, env} = res);
}
}
else if ( term instanceof A ) {
stack.push([ new Tuple(term.right, new Env(env)), true ]);
term = term.left;
} else if ( term instanceof L ) {
const [ { term: lastTerm, env: lastEnv }, isRight, isEvaluated ] = stack.pop();
if ( isEvaluated ) {
// A non-evaluated term was received from an Env, but it is now evaluated.
// Store it.
lastEnv.getValue(lastTerm.name, new Tuple(term, env));
} else if ( isRight ) {
if ( term.name !== "_" )
env = new Env(env).setThunk(term.name, new Tuple(lastTerm, lastEnv));
term = term.body;
} else { // Pass the function some other function.
term = lastTerm(awaitArg(term, env));
}
} else if ( term instanceof Tuple ) {
// for primitives
({term, env} = term);
} else { // Not a term
if ( stack.length === 0 ) return term;
const [ { term: lastTerm, env: lastEnv }, isRight, isEvaluated ] = stack.pop();
if ( isEvaluated ) {
// A non-evaluated term was received from an Env, but it is now evaluated.
// Store it.
lastEnv.getValue(lastTerm.name, new Tuple(term, env));
} else if ( isRight ) {
stack.push([ new Tuple(term, new Env(env)), false ]);
term = lastTerm;
env = lastEnv;
} else { // lastTerm is a JS function
const res = lastTerm(term);
if ( res?.term )
( {term, env=new Env} = res );
else
term = res;
}
}
}
// We need input
return awaitArg(term, env);
}
return runEval(term);
}
// Print an error, with stack trace according to verbosity level
function printStackTrace(error, term, stack) {
if ( config.verbosity >= "Concise" )
console.error(`${ error } inside definition of ${ term.defName }`);
const stackCutoff = config.verbosity < "Verbose" && stack[stack.length-1] == term.defName ? stack.indexOf(term.defName) + 1 : 0 ;
if ( config.verbosity >= "Loquacious" )
console.error( stack.slice(stackCutoff).reverse().map( v => `\twhile evaluating ${ v }`).join('\n') );
}
Object.defineProperty( Function.prototype, "valueOf", { value: function valueOf() { if (this.term) return toInt(this); else return this; } } );