Merge branch 'pryor'
[lambda.git] / code / lambda.js
1 /*jslint bitwise: true,
2     eqeqeq: true,
3     immed: true,
4     newcap: true,
5     nomen: true,
6     onevar: true,
7     plusplus: true,
8     regexp: true,
9     rhino: true,
10     browser: false,
11     undef: true,
12     white: true,
13
14     evil: false,
15     regexp: false,
16     sub: true,
17     laxbreak: true,
18     onevar: false,
19     debug: true */
20
21
22 // DeBruijn terms
23 // substitution and translation algorithms from Chris Hankin, An Introduction to Lambda Calculi for Comptuer Scientists
24 //
25 function Db_free(variable) {
26     this.variable = variable;
27     this.subst = function (m, new_term) {
28         return this;
29     };
30     this.renumber = function (m, i) {
31         return this;
32     };
33     // we assume that other will have variable iff it's a Db_free
34     this.equal = function (other) {
35         return other.variable && this.variable.equal(other.variable);
36     };
37     this.contains = this.equal;
38 }
39
40 function Db_index(i) {
41     this.index = i;
42     this.subst = function (m, new_term) {
43         if (this.index < m) {
44             return this;
45         } else if (this.index > m) {
46             return new Db_index(this.index - 1);
47         } else {
48             return new_term.renumber(this.index, 1);
49         }
50     };
51     this.renumber = function (m, i) {
52         if (this.index < i) {
53             return this;
54         } else {
55             return new Db_index(this.index + m - 1);
56         }
57     };
58     // we assume that other will have index iff it's a Db_index
59     this.equal = function (other) {
60         return this.index === other.index;
61     };
62     this.contains = this.equal;
63 }
64
65 function Db_app(left, right) {
66     this.left = left;
67     this.right = right;
68     this.subst = function (m, new_term) {
69         return new Db_app(this.left.subst(m, new_term), this.right.subst(m, new_term));
70     };
71     this.renumber = function (m, i) {
72         return new Db_app(this.left.renumber(m, i), this.right.renumber(m, i));
73     };
74     // we assume that other will have left iff it's a Db_app
75     this.equal = function (other) {
76         return other.left && this.left.equal(other.left) && this.right.equal(other.right);
77     };
78     this.contains = function (other) {
79         if (other.left && this.left.equal(other.left) && this.right.equal(other.right)) {
80             return true;
81         } else {
82             return this.left.contains(other) || this.right.contains(other);
83         }
84     };
85 }
86
87 function Db_lam(body) {
88     this.body = body;
89     this.subst = function (m, new_term) {
90         return new Db_lam(this.body.subst(m + 1, new_term));
91     };
92     this.renumber = function (m, i) {
93         return new Db_lam(this.body.renumber(m, i + 1));
94     };
95     // we assume that other will have body iff it's a Db_lam
96     this.equal = function (other) {
97         return other.body && this.body.equal(other.body);
98     };
99     this.contains = function (other) {
100         if (other.body && this.body.equal(other.body)) {
101             return true;
102         } else {
103             return this.body.contains(other);
104         }
105     };
106 }
107
108
109 // lambda terms
110 // substitution and normal-order evaluator based on Haskell version by Oleg Kisleyov
111 // http://okmij.org/ftp/Computation/lambda-calc.html#lambda-calculator-haskell
112 //
113 function Variable(name, tag) {
114     this.name = name;
115     this.tag = tag || 0;
116     this.to_string = function () {
117         // append count copies of str to accum
118 //         function markup(accum, count) {
119 //             if (count === 0) {
120 //                 return accum;
121 //             } else {
122 //                 return markup(accum + "'", count - 1);
123 //             }
124 //         }
125 //         return markup(this.name, this.tag);
126                 var s = this.name;
127                 for (var count = 0; count < this.tag; count += 1) {
128                         s += "'";
129                 }
130                 return s;
131     };
132     this.equal = function (other) {
133         return (this.tag === other.tag) && (this.name === other.name);
134     };
135     // position of this in seq
136     this.position = function (seq) {
137         for (var i = 0; i < seq.length; i += 1) {
138             if (this.equal(seq[i])) {
139                 return new Db_index(i + 1);
140             }
141         }
142         return new Db_free(this);
143     };
144 }
145
146 // if v occurs free_in term, returns Some v' where v' is the highest-tagged
147 // variable with the same name as v occurring (free or bound) in term
148 //
149 function free_in(v, term) {
150     var res = term.has_free(v);
151     return res[0] && res[1];
152 }
153
154 function subst(v, new_term, expr) {
155     if (new_term.variable && new_term.variable.equal(v)) {
156         return expr;
157     } else {
158         return expr.subst(v, new_term);
159     }
160 }
161
162 function equal(expr1, expr2) {
163     return expr1.debruijn([]).equal(expr2.debruijn([]));
164 }
165
166 function contains(expr1, expr2) {
167     return expr1.debruijn([]).contains(expr2.debruijn([]));
168 }
169
170
171 function Lambda_var(variable) {
172     this.variable = variable;
173     this.debruijn = function (seq) {
174         return this.variable.position(seq);
175     };
176     this.to_string = function (as_atom) {
177         return this.variable.to_string();
178     };
179     this.has_free = function (v) {
180         if (v.name !== this.variable.name) {
181             return [false, v];
182         } else if (v.tag === this.variable.tag) {
183             return [true, v];
184         } else {
185             return [false, this.variable];
186         }
187     };
188     this.subst = function (v, new_term) {
189         if (this.variable.equal(v)) {
190             return new_term;
191         } else {
192             return this;
193         }
194     };
195     this.check_eta = function () {
196         return this;
197     };
198     this.eval_loop = function (stack, eta) {
199         function unwind(left, stack) {
200 //             if (stack.length === 0) {
201 //                 return left;
202 //             } else {
203 //                 var x = stack[0];
204 //                 var xs = stack.slice(1);
205 //                 return unwind(new Lambda_app(left, x.eval_loop([], eta)), xs);
206 //             }
207                         var res = left, x;
208                         while (stack.length) {
209                                 x = stack.shift();
210                                 // res = new Lambda_app(res, x.eval_loop([], eta));
211                                 res = new Lambda_app(res, reduce(x, eta, false));
212                         }
213                         return res;
214         }
215         // return unwind(this, stack);
216                 // trampoline to, args
217                 return [null, unwind(this, stack)];
218     };
219     this.eval_cbv = function (aggressive) {
220         return this;
221     };
222 }
223
224 function Lambda_app(left, right) {
225     this.left = left;
226     this.right = right;
227     this.debruijn = function (seq) {
228         return new Db_app(this.left.debruijn(seq), this.right.debruijn(seq));
229     };
230     this.to_string = function (as_atom) {
231         var base;
232         if (this.left.left) {
233             base = this.left.to_string() + " " + this.right.to_string(true);
234         } else {
235             base = this.left.to_string(true) + " " + this.right.to_string(true);
236         }
237         if (as_atom) {
238             return "(" + base + ")";
239         } else {
240             return base;
241         }
242     };
243     this.has_free = function (v) {
244         var left_res = this.left.has_free(v);
245         var right_res = this.right.has_free(v);
246         var left_bool = left_res[0];
247         var right_bool = right_res[0];
248         var left_tag = left_res[1].tag;
249         var right_tag = right_res[1].tag;
250         var res;
251         if (left_tag > right_tag) {
252             res = left_res[1];
253         } else {
254             res = right_res[1];
255         }
256         return [left_bool || right_bool, res];
257     };
258     this.subst = function (v, new_term) {
259         return new Lambda_app(subst(v, new_term, this.left), subst(v, new_term, this.right));
260     };
261     this.check_eta = function () {
262         return this;
263     };
264     this.eval_loop = function (stack, eta) {
265         var new_stack = stack.slice(0);
266         new_stack.unshift(this.right);
267         // return this.left.eval_loop(new_stack, eta);
268                 // trampoline to, args
269                 return [this.left, new_stack, eta];
270     };
271     this.eval_cbv = function (aggressive) {
272         var left = this.left.eval_cbv(aggressive);
273         var right = this.right.eval_cbv(aggressive);
274         if (left.body) {
275             return subst(left.bound, right, left.body).eval_cbv(aggressive);
276         } else {
277             return new Lambda_app(left, right);
278         }
279     };
280 }
281
282
283 //     (* if v occurs free_in term, returns Some v' where v' is the highest-tagged
284 //      * variable with the same name as v occurring (free or bound) in term *)
285
286
287 function Lambda_lam(variable, body) {
288     this.bound = variable;
289     this.body = body;
290     this.debruijn = function (seq) {
291         var new_seq = seq.slice(0);
292         new_seq.unshift(this.bound);
293         return new Db_lam(this.body.debruijn(new_seq));
294     };
295     this.to_string = function (as_atom) {
296         var base = "\\" + this.to_string_funct();
297         if (as_atom) {
298             return "(" + base + ")";
299         } else {
300             return base;
301         }
302     };
303     this.to_string_funct = function () {
304         if (this.body.to_string_funct) {
305             return this.bound.to_string() + " " + this.body.to_string_funct();
306         } else {
307             return this.bound.to_string() + ". " + this.body.to_string();
308         }
309     };
310     this.has_free = function (v) {
311         if (this.bound.equal(v)) {
312             return [false, v];
313         } else {
314             return this.body.has_free(v);
315         }
316     };
317     this.subst = function (v, new_term) {
318         function bump_tag(v1, v2) {
319             var max;
320             if (v1.tag > v2.tag) {
321                 max = v1.tag;
322             } else {
323                 max = v2.tag;
324             }
325             return new Variable(v1.name, max + 1);
326         }
327         function bump_tag2(v1, v2) {
328             if (v1.name !== v2.name) {
329                 return v1;
330             } else {
331                 return bump_tag(v1, v2);
332             }
333         }
334         if (this.bound.equal(v)) {
335             return this;
336         } else {
337             var res = free_in(this.bound, new_term);
338             // if x is free in the inserted term new_term, a capture is possible
339             if (res) {
340                 // this.bound is free in new_term, need to alpha-convert
341                 var uniq_x = bump_tag2(bump_tag(this.bound, res), v);
342                 var res2 = free_in(uniq_x, this.body);
343                 if (res2) {
344                     uniq_x = bump_tag(uniq_x, res2);
345                 }
346                 var body2 = subst(this.bound, new Lambda_var(uniq_x), this.body);
347                 return new Lambda_lam(uniq_x, subst(v, new_term, body2));
348             } else {
349                 // this.bound not free in new_term, can substitute new_term for v without any captures
350                 return new Lambda_lam(this.bound, subst(v, new_term, this.body));
351             }
352         }
353     };
354     this.check_eta = function () {
355         if (this.body.right && this.body.right.variable && this.bound.equal(this.body.right.variable) && !free_in(this.bound, this.body.left)) {
356             return this.body.left;
357         } else {
358             return this;
359         }
360     };
361     this.eval_loop = function (stack, eta) {
362         if (stack.length === 0) {
363                         // var term = new Lambda_lam(this.bound, this.body.eval_loop([], eta));
364                         var term = new Lambda_lam(this.bound, reduce(this.body, eta, false));
365                         if (eta) {
366                                 return [null, term.check_eta()];
367                         } else {
368                                 return [null, term];
369                         }
370         } else {
371             var x = stack[0];
372             var xs = stack.slice(1);
373             // return subst(this.bound, x, this.body).eval_loop(xs, eta);
374                         // trampoline to, args
375                         return [subst(this.bound, x, this.body), xs, eta];
376         }
377     };
378     this.eval_cbv = function (aggressive) {
379         if (aggressive) {
380             return new Lambda_lam(this.bound, this.body.eval_cbv(aggressive));
381         } else {
382             return this;
383         }
384     };
385     this.to_int = function (sofar) {
386 //         if (this.body.body && this.body.body.variable && this.body.bound.equal(this.body.body.variable)) {
387 //             return 0 + sofar;
388 //         } else if (this.body.variable && this.bound.equal(this.body.variable)) {
389 //             return 1 + sofar;
390 //         } else if (this.body.body && this.body.body.left && this.body.body.left.variable && this.bound.equal(this.body.body.left.variable)) {
391 //             var new_int = new Lambda_lam(this.bound, new Lambda_lam(this.body.bound, this.body.body.right));
392 //             return new_int.to_int(1 + sofar);
393 //         } else {
394 //             return "not a church numeral";
395 //         }
396                 var res = 0, s = this.bound, z, cursor;
397                 if (this.body.variable && s.equal(this.body.variable)) {
398                         return 1;
399                 } else if (this.body.bound) {
400                         z = this.body.bound;
401                         cursor = this.body.body;
402                         while (cursor.left && cursor.left.variable && s.equal(cursor.left.variable)) {
403                                 res += 1;
404                                 cursor = cursor.right;
405                         }
406                         if (cursor.variable && z.equal(cursor.variable)) {
407                                 return res;
408                         }
409                 }
410                 return "not a church numeral";
411     };
412 }
413
414
415
416 ///////////////////////////////////////////////////////////////////////////////////
417
418 // cbv is false: use call-by-name
419 // cbv is 1: use call-by-value, don't descend inside lambda
420 // cbv is 2: applicative order
421 function reduce(expr, eta, cbv) {
422     if (cbv) {
423         return expr.eval_cbv(cbv > 1);
424     } else {
425         // return expr.eval_loop([], eta);
426                 var to_eval = expr, res = [[], eta];
427                 while (to_eval !== null) {
428                         res = to_eval.eval_loop.apply(to_eval, res);
429                         to_eval = res.shift();
430                 }
431                 return res[0];
432     }
433 }
434
435 function make_var(name) {
436     return new Variable(name);
437 }
438 function make_app(aa, bb) {
439     return new Lambda_app(aa, bb);
440 }
441 function make_lam(a, aa) {
442     return new Lambda_lam(a, aa);
443 }
444
445 try {
446     if (console && console.debug) {
447         function print() {
448             console.debug.apply(this, arguments);
449         }
450     }
451 } catch (e) {}
452
453 /*
454 let true = K in
455 let false = \x y. y in
456 let and = \l r. l r false in
457 let or = \l r. l true r in
458 let pair = \u v f. f u v in
459 let triple = \u v w f. f u v w in
460 let succ = \n s z. s (n s z) in
461 let pred = \n s z. n (\u v. v (u s)) (K z) I in
462 let ifzero = \n. n (\u v. v (u succ)) (K 0) (\n withp whenz. withp n) in
463 let add = \m n. n succ m in
464 let mul = \m n. n (\z. add m z) 0 in
465 let mul = \m n s. m (n s) in
466 let sub = (\mzero msucc mtail. \m n. n mtail (m msucc mzero) true) (pair 0 I) (\d. d (\a b. pair (succ a) (K d))) (\d. d false d) in
467 let min = \m n. sub m (sub m n) in
468 let max = \m n. add n (sub m n) in
469 let lt = (\mzero msucc mtail. \n m. n mtail (m msucc mzero) true (\x. true) false) (pair 0 I) (\d. d (\a b. pair (succ a) (K d))) (\d. d false d) in
470 let leq = (\mzero msucc mtail. \m n. n mtail (m msucc mzero) true (\x. false) true) (pair 0 I) (\d. d (\a b. pair (succ a) (K d))) (\d. d false d) in
471 let eq = (\mzero msucc mtail. \m n. n mtail (m msucc mzero) true (\x. false) true) (pair 0 (K (pair 1 I))) (\d. d (\a b. pair (succ a) (K d))) (\d. d false d) in
472 let divmod = (\mzero msucc mtail. \n divisor.
473                (\dhead. n (mtail dhead) (\sel. dhead (sel 0 0)))
474               (divisor msucc mzero (\a b c. c x))
475               (\d m a b c. pair d m) )
476           (triple succ (K 0) I)
477           (\d. triple I succ (K d))
478           (\dhead d. d (\dz mz df mf drest sel. drest dhead (sel (df dz) (mf mz)))) in
479 let div = \n d. divmod n d true in
480 let mod = \n d. divmod n d false in
481 let Y = \f. (\y. f(y y)) (\y. f(y y)) in
482 let Z = (\u f. f(u u f)) (\u f. f(u u f)) in
483 let fact = \y. y (\f n. ifzero n (\p. mul n (f p)) 1) in
484 fact Z 3
485 */
486
487
488
489 // // Basic data structure, essentially a LISP/Scheme-like cons
490 // // pre-terminal nodes are expected to be of the form new cons(null, "string")
491 // function cons(car, cdr) {
492 //   this.car = car;
493 //   this.cdr = cdr;
494 // }
495
496 // // takes a stack of symbols, returns a pair: a tree and the remaining symbols
497 // function parse(split) {
498 //   if (split == null) return (new cons (null, null));
499 //   if (split.length == 0) return (new cons (null, null));
500 //   var token = split.shift();
501 //   if (token == ")") return (new cons (null, split));
502 //   var next = parse(split);
503 //   if (token == "(") {
504 //     var nextnext = parse(next.cdr);
505 //     return (new cons ((new cons (next.car, nextnext.car)),
506 //                       nextnext.cdr));
507 //   }
508 //   return (new cons ((new cons ((new cons (null, token)),
509 //                                next.car)),
510 //                     next.cdr))
511 // }
512
513 // // substitute arg in for v in tree
514 // function sub(tree, v, arg) {
515 //   if (tree == null) return (null);
516 //   if (tree.car == null) if (tree.cdr == v) return (arg);
517 //   if (tree.car == null) return (tree);
518
519 //   // perform alpha reduction to prevent variable collision
520 //   if (isBindingForm(tree)) 
521 //     return (new cons (tree.car, 
522 //                       sub(sub(tree.cdr,         // inner sub = alpha reduc.
523 //                               tree.cdr.car.cdr, 
524 //                               fresh(tree.cdr.car.cdr)),
525 //                           v,
526 //                           arg)));
527
528 //   return (new cons ((sub (tree.car, v, arg)),
529 //                     (sub (tree.cdr, v, arg))))
530 // }
531
532 // // Guaranteed unique for each call as long as string is not empty.
533 // var i = 0;
534 // function fresh(string) {
535 //   i = i+1;
536 //   if (typeof(string) != "string") return (string);
537 //   return (new cons (null,  
538 //                     string.substring(0,1) + (i).toString()));
539 // }
540
541 // // Keep reducing until there is no more change
542 // function fixedPoint (tree) {
543 //   var t2 = reduce(tree);
544 //   if (treeToString(tree) == treeToString(t2)) return (tree);
545 //   return (fixedPoint (t2));
546 // }
547
548 // // Reduce all the arguments, then try to do beta conversion on the whole
549 // function reduce(tree) {
550 //   if (tree == null) return (tree);
551 //   if (typeof(tree) == "string") return (tree);
552 //   return (convert (new cons (reduce (tree.car), mapReduce (tree.cdr))));
553 // }
554
555 // // Reduce all the arguments in a list
556 // function mapReduce(tree) {
557 //   if (tree == null) return (tree);
558 //   if (tree.car == null) return (tree);
559 //   return (new cons (reduce (tree.car), mapReduce(tree.cdr )));
560 // }
561
562 // // If the list is of the form ((lambda var body) arg), do beta reduc.
563 // function convert(tree) {
564 //     if (isLet(tree)) {
565 //       return (sub(tree.cdr.car, tree.car.cdr.car.cdr, tree.car.cdr.cdr.car));}
566 //     else 
567 //       if (isConvertable(tree)) {
568 //         return (sub(tree.car.cdr.cdr.car, tree.car.cdr.car.cdr, tree.cdr.car));}
569 //       else return(tree);
570 // } 
571
572 // // Is of form ((let var arg) body)?
573 // function isLet(tree) {
574 //   if (tree == null) return (false);
575 //   if (!(isBindingForm(tree.car))) return (false);
576 //   if (tree.car.car.cdr != "let") return (false);
577 //   if (tree.cdr == null) return (false);
578 //   if (tree.cdr.car == null) return (false);
579 //   return(true);
580 // }  
581
582 // // Is of form ((lambda var body) arg)?
583 // function isConvertable(tree) {
584 //   if (tree == null) return (false);
585 //   if (!(isBindingForm(tree.car))) return (false);
586 //   if (tree.car.car.cdr != "lambda") return (false);
587 //   if (tree.cdr == null) return (false);
588 //   if (tree.cdr.car == null) return (false);
589 //   return(true);
590 // }  
591
592 // // Is of form (lambda var body)?
593 // function isBindingForm(tree) {
594 //   if (tree == null) return (false);
595 //   if (tree.car == null) return (false);
596 //   if (tree.car.car != null) return (false);
597 //   if ((tree.car.cdr != "lambda") 
598 //       && (tree.car.cdr != "let")
599 //       && (tree.car.cdr != "exists")
600 //       && (tree.car.cdr != "forall")
601 //       && (tree.car.cdr != "\u03BB")
602 //       && (tree.car.cdr != "\u2200")
603 //       && (tree.car.cdr != "\u2203")
604 //      )
605 //     return (false);
606 //   if (tree.car.cdr == null) return (false);
607 //   if (tree.cdr.car == null) return (false);
608 //   if (tree.cdr.car.car != null) return (false);
609 //   if (tree.cdr.cdr == null) return (false);
610 //   return (true);
611 // }
612
613 // function treeToString(tree) {
614 //   if (tree == null) return ("")
615 //   if (tree.car == null) return (tree.cdr)
616 //   if ((tree.car).car == null) 
617 //     return (treeToString(tree.car) + " " + treeToString(tree.cdr))
618 //   return ("(" + treeToString(tree.car) + ")" + treeToString(tree.cdr))
619 // }
620
621 // // use this instead of treeToString if you want to see the full structure
622 // function treeToStringRaw(tree) {
623 //   if (tree == null) return ("@")
624 //   if (typeof(tree) == "string") return (tree);
625 //   return ("(" + treeToStringRaw(tree.car) + "." + 
626 //                 treeToStringRaw(tree.cdr) + ")")
627 // }
628
629 // // Make sure each paren will count as a separate token
630 // function stringToTree(input) {
631 //   input = input.replace(/let/g, " ( ( let ");
632 //   input = input.replace(/=/g, " ");
633 //   input = input.replace(/in/g, " ) ");
634 //   input = input.replace(/\(/g, " ( ");
635 //   input = input.replace(/\)/g, " ) ");
636 //   input = input.replace(/;.*\n/g," ");
637 //   input = input.replace(/\^/g, " ^ ");
638 //   input = input.replace(/[\\]/g, " lambda ");
639 //   input = input.replace(/\u03BB/g, " lambda ");
640 //   return ((parse(input.split(/[ \f\n\r\t\v]+/))).car)
641 // }
642
643 // // Adjust spaces to print pretty
644 // function formatTree(tree) {
645 //   output = treeToStringRaw (tree);
646 //   output = output.replace(/^[ \f\n\r\t\v]+/, "");
647 //   output = output.replace(/[ \f\n\r\t\v]+$/, "");
648 //   output = output.replace(/[ \f\n\r\t\v]+\)/g, ")");
649 //   output = output.replace(/\)([^)(])/g, ") $1");
650 //   output = output.replace(/lambda/g, "\\");
651 // //  output = output.replace(/lambda/g, "\u03BB");
652 // //  output = output.replace(/exists/g, "\u2203");
653 // //  output = output.replace(/forall/g, "\u2200");
654 //   return (output)
655 // }
656
657 // function mytry(form) { 
658 //   i = 0;
659 //   form.result.value = formatTree((stringToTree(form.input.value)));
660 //   // form.result.value = formatTree(fixedPoint(stringToTree(form.input.value)));
661 // }