government / src / eval / logic_test.go

@ a94ce18dbaa3c27d01f1491d51ec12c5767daf6d | history


package eval

import "testing"

func TestAndOr(t *testing.T) {
	runEvalCases(t, []evalCase{
		{"(and)", "T"},
		{"(and T)", "T"},
		{"(and F)", "F"},
		{"(and 1 2)", "2"},
		{`(and T "yes")`, `"yes"`},
		{"(and 1 F 3)", "F"},
		{"(and 0 () \"\")", `""`},
		{"(or)", "F"},
		{"(or F)", "F"},
		{"(or 7)", "7"},
		{"(or F 7)", "7"},
		{"(or F F)", "F"},
		{"(or F () 3)", "()"},
		{"(or 1 2)", "1"},

		// Operands after the deciding one are never evaluated.
		{"(and F (car '()))", "F"},
		{"(and F boom)", "F"},
		{"(or 1 (car '()))", "1"},
		{"(or T boom)", "T"},

		{"(and (or F 1) (or F 2))", "2"},
		{"(or (and 1 F) (and 2 3))", "3"},
		{"(not (and T F))", "T"},
		{"(if (and (< 1 2) (< 2 3)) 'ordered 'not)", "ordered"},

		// The "value or default" idiom.
		{"(define lookup (lambda (k) (if (== k 'a) 1 F))) (or (lookup 'a) 0)", "1"},
		{"(define lookup (lambda (k) (if (== k 'a) 1 F))) (or (lookup 'b) 0)", "0"},

		{`(define member? (lambda (x l) (and (!= l ()) (or (== x (car l)) (member? x (cdr l))))))
		  (cons (member? 2 '(1 2 3)) (member? 4 '(1 2 3)))`, "(T . F)"},
	})
}

func TestAndOrErrors(t *testing.T) {
	runErrorCases(t, []errorCase{
		// Operands are evaluated left to right until one decides.
		{"(and T boom)", ErrUnbound, "no statute for symbol boom"},
		{"(or F boom)", ErrUnbound, "no statute for symbol boom"},
		{"(and (car '()) boom)", ErrType, "car needs a pair, got ()"},
		{"(or (car '()) boom)", ErrType, "car needs a pair, got ()"},

		{"and", ErrSpecialForm, "and is a special form, not a value"},
		{"(cons or ())", ErrSpecialForm, "or is a special form, not a value"},
		{"(lambda (and) 1)", ErrSyntax, "lambda parameter and is a reserved name"},
		{"(define or 1)", ErrSyntax, "cannot define reserved name or"},
	})
}