government

commit 0fff601606926403bf0266dd4ab33726a7814f2d

tree

parent:
b048340a0d68f9609a801d8b97e45aed81821ab5

nmyk <nick@nmyk.io>

2026-11-14T13:03:17-05:00

add define

diff --git a/DESIGN.md b/DESIGN.md
index 445564550383fd18ffa44706c94f46d3d1f208e7..b0eff7a836a4f710ec4f7882353facccb459b621 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -215,7 +215,7 @@ | Boolean | `T` or `F` | `T`, `F` |
 | Symbol | interned name | `foo` |
 | Pair | immutable (car, cdr) | `(1 2 3)`, `(1 . 2)` |
 | Empty list | unique value | `()` |
-| Function | closure or builtin | `#<lambda>`, `#<builtin +>` |
+| Function | closure or builtin | `#<lambda fact>`, `#<lambda>`, `#<builtin +>` |
 
 Lists are pairs ending in `()`.
 
@@ -233,7 +233,7 @@
 - **Truthiness.** As in Scheme, `F` is the only false value. Everything else is true, including `0`, `0.0`, `""` and `()`.
 - **`(quote d)`** returns `d` as data, unevaluated. Atoms become their values. Builtin nodes become symbols of the same name (`'+` is the symbol `+`), except `T`/`F` (booleans) and `()` (lists).
 - **`(if c a b)`** evaluates `a` unless `c` is `F`, in which case it evaluates `b`. **`(if c a)`** returns `()` when `c` is `F`. Only the selected branch is evaluated.
-- **`(define name expr)`** is allowed at top level and at the start of a lambda body, before any expression. It returns the symbol `name`. Scoping rules are below.
+- **`(define name expr)`** is allowed at top level and at the start of a lambda body, before any expression. It returns the symbol `name`. When the value is a `lambda` written directly in the `define`, the closure takes `name` for printing and error messages (`#<lambda fact>`, `fact takes 1 argument, got 2`); binding it again later does not rename it. Scoping rules are below.
 - **`(lambda (p1 … pk) body…)`** creates a closure over the current environment. It takes a fixed number of parameters (no variadic lambdas), which must be distinct symbols. The body is zero or more `define`s followed by one or more expressions; the last expression's value is returned. Calling with the wrong number of arguments is an error.
 - **`(and x…)`** evaluates left to right and returns `F` at the first `F`; otherwise it returns the last value. `(and)` is `T`.
 - **`(or x…)`** evaluates left to right and returns the first value that is not `F`; otherwise `F`. `(or)` is `F`.
@@ -254,7 +254,7 @@ - The environment is a chain of single, immutable bindings. Each `define` extends the chain; nothing is ever changed in place.
 - The new binding is visible inside its own `expr`, so `(define fact (lambda (n) … (fact …)))` works. Using it before it has a value, as in `(define x (+ x 1))`, is an error.
 - Any reference to a name defined later in the same scope is an unbound-symbol error, even from inside a lambda. That is what rules out mutual recursion.
 - The same rule applies at top level, so top-level functions cannot be mutually recursive either.
-- Defining a name twice in the same scope is an error (immutable bindings). A lambda parameter or an inner `define` may shadow an outer name.
+- Defining a name twice in the same scope is an error (immutable bindings). As in Scheme, the `define`s at the start of a lambda body form their own scope inside the parameters' scope, so a `define` may shadow a parameter. A lambda parameter or an inner `define` may shadow an outer name.
 
 ### Builtin functions
 
diff --git a/eval/builtin.go b/eval/builtin.go
index 5d0f3dab1ea0e9469446f3f3168393842ab0435a..7fcb411f0432274f883140f7661903c884ce702b 100644
--- a/eval/builtin.go
+++ b/eval/builtin.go
@@ -18,7 +18,8 @@ 	minArgs, maxArgs int
 	fn               func(args []sexpr.Value) (sexpr.Value, error)
 }
 
-func (b *Builtin) Name() string { return b.name }
+func (b *Builtin) Builtin() bool { return true }
+func (b *Builtin) Name() string  { return b.name }
 
 var builtins = []*Builtin{
 	{name: "+", minArgs: 0, maxArgs: -1, fn: add},
diff --git a/eval/closure.go b/eval/closure.go
index 2e8542af041ab35565d18512a1071b4f38335b74..d674df009652cdc2eef2323eabadb2171c61d463 100644
--- a/eval/closure.go
+++ b/eval/closure.go
@@ -8,15 +8,25 @@ // what makes scope lexical.
 type Closure struct {
 	sexpr.FunctionBase
 	params []sexpr.Symbol
-	body   []sexpr.Value
+	body   []sexpr.Value // defines first, then at least one expression
 	env    *Env
+	name   string // set by the first define that binds it; "" if anonymous
 }
 
-func (*Closure) Name() string { return "" }
+func (*Closure) Builtin() bool  { return false }
+func (c *Closure) Name() string { return c.name }
+
+func (c *Closure) displayName() string {
+	if c.name == "" {
+		return "lambda"
+	}
+	return c.name
+}
 
 // (lambda (p1 ... pk) body...)
 //
-// The parameter list is checked once, here, rather than on every call.
+// The parameter list and the shape of the body are checked once, here,
+// rather than on every call.
 func evalLambda(operands []sexpr.Value, env *Env) (sexpr.Value, error) {
 	if len(operands) == 0 {
 		return nil, errorf(ErrSyntax, "lambda needs a parameter list and a body")
@@ -29,9 +39,31 @@ 	body := operands[1:]
 	if len(body) == 0 {
 		return nil, errorf(ErrSyntax, "lambda needs a body")
 	}
+	if err := checkBodyShape(body); err != nil {
+		return nil, err
+	}
 	return &Closure{params: params, body: body, env: env}, nil
 }
 
+// checkBodyShape enforces: zero or more defines, then one or more
+// expressions.
+func checkBodyShape(body []sexpr.Value) error {
+	defines := 0
+	for i, form := range body {
+		if !isFormNamed(form, "define") {
+			continue
+		}
+		if i != defines {
+			return errorf(ErrSyntax, "define must come before any expression in a lambda body")
+		}
+		defines++
+	}
+	if defines == len(body) {
+		return errorf(ErrSyntax, "lambda body needs an expression after its definitions")
+	}
+	return nil
+}
+
 func parseParams(v sexpr.Value) ([]sexpr.Symbol, error) {
 	items, ok := properList(v)
 	if !ok {
@@ -57,20 +89,29 @@ 	return params, nil
 }
 
 // applyClosure binds each parameter to its argument in the closure's own
-// environment, then evaluates the body forms in order. The value of the
-// last one is the result.
+// environment, runs the body's defines, then evaluates its expressions in
+// order. The value of the last one is the result.
+//
+// As in Scheme, the body's defines form their own scope nested inside the
+// parameters', so a define may shadow a parameter.
 func applyClosure(c *Closure, args []sexpr.Value) (sexpr.Value, error) {
 	if len(args) != len(c.params) {
-		return nil, errorf(ErrArity, "lambda takes %s, got %d", plural(len(c.params), "argument"), len(args))
+		return nil, errorf(ErrArity, "%s takes %s, got %d", c.displayName(), plural(len(c.params), "argument"), len(args))
 	}
 	env := c.env
 	for i, p := range c.params {
 		env = env.Extend(p, args[i])
 	}
+	s := newScope(env)
 	var result sexpr.Value
 	for _, form := range c.body {
 		var err error
-		if result, err = Eval(form, env); err != nil {
+		if items, ok := defineForm(form); ok {
+			_, err = s.define(items)
+		} else {
+			result, err = Eval(form, s.env)
+		}
+		if err != nil {
 			return nil, err
 		}
 	}
diff --git a/eval/define.go b/eval/define.go
new file mode 100644
index 0000000000000000000000000000000000000000..11ddad94fb4681ab4318e8e912639700d89b9042
--- /dev/null
+++ b/eval/define.go
@@ -0,0 +1,90 @@
+package eval
+
+import "government/sexpr"
+
+// A scope is one run of sequential definitions: the top level of a program,
+// or the defines at the start of one lambda call's body. Each define extends env, so a definition sees the ones before
+// it and itself, never the ones after it: self-recursion works, mutual
+// recursion does not.
+type scope struct {
+	env   *Env
+	names map[sexpr.Symbol]bool
+}
+
+func newScope(env *Env) *scope {
+	return &scope{env: env, names: map[sexpr.Symbol]bool{}}
+}
+
+// define evaluates (define name expr) and adds name to the scope.
+func (s *scope) define(form []sexpr.Value) (sexpr.Value, error) {
+	if len(form) != 3 {
+		return nil, errorf(ErrSyntax, "define takes a name and a value, got %s", plural(len(form)-1, "operand"))
+	}
+	name, ok := form[1].(sexpr.Symbol)
+	if !ok {
+		return nil, errorf(ErrSyntax, "define needs a symbol name, got %s", sexpr.Print(form[1]))
+	}
+	if isReserved(name) {
+		return nil, errorf(ErrSyntax, "cannot define reserved name %s", name)
+	}
+	if s.names[name] {
+		return nil, errorf(ErrImmutable, "%s is already defined in this scope; bindings are immutable", name)
+	}
+
+	slot := s.env.extendPending(name)
+	v, err := Eval(form[2], slot)
+	if err != nil {
+		return nil, err
+	}
+	// A closure takes the name it is first defined under, for printing and
+	// error messages. Only a lambda written directly in the define is
+	// named: (define g f) must not rename f's closure.
+	if c, ok := v.(*Closure); ok && isFormNamed(form[2], "lambda") {
+		c.name = string(name)
+	}
+	slot.fill(v)
+	s.env = slot
+	s.names[name] = true
+	return name, nil
+}
+
+// TopLevel evaluates a program one top-level form at a time, keeping the
+// definitions made so far.
+type TopLevel struct {
+	scope *scope
+}
+
+func NewTopLevel() *TopLevel {
+	return NewTopLevelIn(Builtins())
+}
+
+// NewTopLevelIn starts a program in env instead of the builtins alone.
+func NewTopLevelIn(env *Env) *TopLevel {
+	return &TopLevel{scope: newScope(env)}
+}
+
+func (t *TopLevel) Eval(form sexpr.Value) (sexpr.Value, error) {
+	if items, ok := defineForm(form); ok {
+		return t.scope.define(items)
+	}
+	return Eval(form, t.scope.env)
+}
+
+// define reached through Eval is in expression position, such as inside an
+// if. Scope-level code intercepts the defines that are allowed before they
+// get here.
+func evalMisplacedDefine(operands []sexpr.Value, env *Env) (sexpr.Value, error) {
+	return nil, errorf(ErrSyntax, "define is only allowed at top level or at the start of a lambda body")
+}
+
+func defineForm(v sexpr.Value) ([]sexpr.Value, bool) {
+	if !isFormNamed(v, "define") {
+		return nil, false
+	}
+	return properList(v)
+}
+
+func isFormNamed(v sexpr.Value, head sexpr.Symbol) bool {
+	p, ok := v.(*sexpr.Pair)
+	return ok && p.Car == sexpr.Value(head)
+}
diff --git a/eval/define_test.go b/eval/define_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0c76c243e254789fd359343af9cdbcbb32111950
--- /dev/null
+++ b/eval/define_test.go
@@ -0,0 +1,96 @@
+package eval
+
+import "testing"
+
+func TestDefine(t *testing.T) {
+	runEvalCases(t, []evalCase{
+		{"(define y 5)", "y"},
+		{"(define y 5) y", "5"},
+		{"(define y 5) (define z (+ y 1)) (* y z)", "30"},
+		{"(define add +) (add 2 3)", "5"},
+		{"(define sq (lambda (n) (* n n))) (sq 7)", "49"},
+
+		// Self-recursion: the name is visible inside its own definition.
+		{`(define fact (lambda (n) (if (== n 0) 1 (* n (fact (- n 1))))))
+		  (fact 10)`, "3628800"},
+		{`(define fib (lambda (n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
+		  (fib 15)`, "610"},
+		{`(define len (lambda (l) (if (== l ()) 0 (+ 1 (len (cdr l))))))
+		  (len '(a b c d))`, "4"},
+
+		// A top-level define may shadow a name from an enclosing
+		// environment: the test env binds x outside the program's scope.
+		{"(define x 2) x", "2"},
+
+		// The design's scoping test, now with define.
+		{`(define x 1)
+		  (define f (lambda () x))
+		  (define g (lambda (x) (f)))
+		  (g 2)`, "1"},
+
+		// Defines at the start of a lambda body are sequential.
+		{"((lambda (x) (define y (+ x 1)) (define z (+ y 1)) z) 1)", "3"},
+		{"((lambda () (define a 1) (define b (+ a 1)) (cons a (cons b ()))))", "(1 2)"},
+
+		// Body defines are a scope inside the parameters', so they may
+		// shadow a parameter. Earlier defines still see the parameter.
+		{"((lambda (x) (define x 2) x) 1)", "2"},
+		{"((lambda (x) (define y x) (define x 3) (+ x y)) 1)", "4"},
+
+		// An inner define shadows an outer one without changing it.
+		{"(define y 1) ((lambda () (define y 2) y))", "2"},
+		{"(define y 1) ((lambda () (define y 2) y)) y", "1"},
+
+		// Each call gets a fresh scope, so the same body can run twice.
+		{`(define twice (lambda (n) (define m (* n 2)) m))
+		  (+ (twice 1) (twice 10))`, "22"},
+
+		// Closures remember the name they were first defined under.
+		{"(define sq (lambda (n) (* n n))) sq", "#<lambda sq>"},
+		{"(define sq (lambda (n) (* n n))) (define square sq) square", "#<lambda sq>"},
+		{"(define make (lambda () (lambda () 1))) (define g (make)) g", "#<lambda>"},
+		{"(define make (lambda () (lambda () 1))) make", "#<lambda make>"},
+		{"(lambda () 1)", "#<lambda>"},
+		{"((lambda () (define inner (lambda () 1)) inner))", "#<lambda inner>"},
+	})
+}
+
+func TestDefineErrors(t *testing.T) {
+	runErrorCases(t, []errorCase{
+		{"(define y 1) (define y 2)", ErrImmutable, "y is already defined in this scope; bindings are immutable"},
+		{"((lambda () (define a 1) (define a 2) a))", ErrImmutable, "a is already defined in this scope; bindings are immutable"},
+
+		{"(define y (+ y 1))", ErrUnbound, "y is used before its definition is complete"},
+		{"(define x (+ x 1))", ErrUnbound, "x is used before its definition is complete"},
+		{"(define y (car (cons y 1)))", ErrUnbound, "y is used before its definition is complete"},
+		// The new x shadows the parameter from the moment the define starts.
+		{"((lambda (x) (define x (+ x 1)) x) 1)", ErrUnbound, "x is used before its definition is complete"},
+
+		// Mutual recursion is excluded: a's closure was created before b
+		// existed, so b is not in its environment.
+		{"((lambda () (define a (lambda () (b))) (define b (lambda () 1)) (a)))", ErrUnbound, "no statute for symbol b"},
+		{"(define even? (lambda (n) (if (== n 0) T (odd? (- n 1))))) (define odd? (lambda (n) (if (== n 0) F (even? (- n 1))))) (even? 4)", ErrUnbound, "no statute for symbol odd?"},
+
+		{"(define)", ErrSyntax, "define takes a name and a value, got 0 operands"},
+		{"(define y)", ErrSyntax, "define takes a name and a value, got 1 operand"},
+		{"(define y 1 2)", ErrSyntax, "define takes a name and a value, got 3 operands"},
+		{"(define 1 2)", ErrSyntax, "define needs a symbol name, got 1"},
+		{"(define (f x) x)", ErrSyntax, "define needs a symbol name, got (f x)"},
+		{"(define + 1)", ErrSyntax, "cannot define reserved name +"},
+		{"(define if 1)", ErrSyntax, "cannot define reserved name if"},
+		{"(define define 1)", ErrSyntax, "cannot define reserved name define"},
+
+		{"(if T (define y 1))", ErrSyntax, "define is only allowed at top level or at the start of a lambda body"},
+		{"(+ 1 (define y 1))", ErrSyntax, "define is only allowed at top level or at the start of a lambda body"},
+		{"((lambda () ((lambda () (if T (define z 1) 0))) 1))", ErrSyntax, "define is only allowed at top level or at the start of a lambda body"},
+		{"(lambda () 1 (define y 2) y)", ErrSyntax, "define must come before any expression in a lambda body"},
+		{"(lambda () (define y 2))", ErrSyntax, "lambda body needs an expression after its definitions"},
+		{"define", ErrSpecialForm, "define is a special form, not a value"},
+		{"(lambda (define) 1)", ErrSyntax, "lambda parameter define is a reserved name"},
+
+		// Errors name the function when it has one.
+		{"(define sq (lambda (n) (* n n))) (sq)", ErrArity, "sq takes 1 argument, got 0"},
+		{"(define sq (lambda (n) (* n n))) (define square sq) (square 1 2)", ErrArity, "sq takes 1 argument, got 2"},
+		{"((lambda (n) n))", ErrArity, "lambda takes 1 argument, got 0"},
+	})
+}
diff --git a/eval/env.go b/eval/env.go
index a4faacac8fa8ecc280104fc1a5f3ad470c003da4..347aebc63a9b1f3f3c9a630e7beaf42bd280d66e 100644
--- a/eval/env.go
+++ b/eval/env.go
@@ -2,17 +2,24 @@ package eval
 
 import "government/sexpr"
 
-// Env is a lexical environment: an immutable linked list of bindings,
-// innermost first. The nil *Env is the empty environment.
+// Env is a lexical environment: a linked list of bindings, innermost first.
+// The nil *Env is the empty environment.
 //
 // Extending returns a new head that points at the old list, so a closure
 // can capture an environment just by keeping the pointer: later extensions
 // by anyone else are invisible to it. Lookup walks the chain, so the first
 // match is the innermost binding, which is what makes shadowing work.
+//
+// Bindings never change, with one exception that exists for recursion: a
+// define creates its binding empty (pending), evaluates the value in an
+// environment that already contains the binding, then fills it exactly
+// once. Until then any use of the name is an error, so no one can observe
+// the binding changing.
 type Env struct {
-	name   sexpr.Symbol
-	value  sexpr.Value
-	parent *Env
+	name    sexpr.Symbol
+	value   sexpr.Value
+	pending bool
+	parent  *Env
 }
 
 func (e *Env) Extend(name sexpr.Symbol, value sexpr.Value) *Env {
@@ -20,10 +27,27 @@ 	return &Env{name: name, value: value, parent: e}
 }
 
 func (e *Env) Lookup(name sexpr.Symbol) (sexpr.Value, bool) {
+	b := e.binding(name)
+	if b == nil || b.pending {
+		return nil, false
+	}
+	return b.value, true
+}
+
+func (e *Env) binding(name sexpr.Symbol) *Env {
 	for b := e; b != nil; b = b.parent {
 		if b.name == name {
-			return b.value, true
+			return b
 		}
 	}
-	return nil, false
+	return nil
+}
+
+func (e *Env) extendPending(name sexpr.Symbol) *Env {
+	return &Env{name: name, pending: true, parent: e}
+}
+
+func (e *Env) fill(value sexpr.Value) {
+	e.value = value
+	e.pending = false
 }
diff --git a/eval/error.go b/eval/error.go
index 8c4e1bb34973a7542b811ee83a92acfc556e9a88..633f8b7dc7104cbbc37f131f79f20c74e6ccae6d 100644
--- a/eval/error.go
+++ b/eval/error.go
@@ -11,6 +11,7 @@ 	ErrNotAFunction = "E-NOT-A-FUNCTION"
 	ErrArity        = "E-ARITY"
 	ErrType         = "E-TYPE"
 	ErrArith        = "E-ARITH"
+	ErrImmutable    = "E-IMMUTABLE"
 )
 
 type Error struct {
diff --git a/eval/eval.go b/eval/eval.go
index 031daba4eab67f18fbc298e6ebd5647498f71ae4..242d5c9a99742cf77287d0473a617b94b59e59a0 100644
--- a/eval/eval.go
+++ b/eval/eval.go
@@ -15,6 +15,7 @@ 	specialForms = map[sexpr.Symbol]specialForm{
 		"quote":  evalQuote,
 		"if":     evalIf,
 		"lambda": evalLambda,
+		"define": evalMisplacedDefine,
 	}
 }
 
@@ -37,11 +38,14 @@ func evalSymbol(name sexpr.Symbol, env *Env) (sexpr.Value, error) {
 	if _, ok := specialForms[name]; ok {
 		return nil, errorf(ErrSpecialForm, "%s is a special form, not a value", name)
 	}
-	v, ok := env.Lookup(name)
-	if !ok {
+	b := env.binding(name)
+	switch {
+	case b == nil:
 		return nil, errorf(ErrUnbound, "no statute for symbol %s", name)
+	case b.pending:
+		return nil, errorf(ErrUnbound, "%s is used before its definition is complete", name)
 	}
-	return v, nil
+	return b.value, nil
 }
 
 func evalList(list *sexpr.Pair, env *Env) (sexpr.Value, error) {
diff --git a/eval/eval_test.go b/eval/eval_test.go
index 3f8e08a458a25cadb77d5fb9e587e1d95b58bef6..1be3168ca4003b0aad7bbfd6aacd7c7be536747f 100644
--- a/eval/eval_test.go
+++ b/eval/eval_test.go
@@ -17,16 +17,25 @@ 		Extend("no", sexpr.F).
 		Extend("empty", sexpr.Nil)
 }
 
+// evalString evaluates every top-level form in src, in order, and returns
+// the last value or the first error.
 func evalString(t *testing.T, src string) (sexpr.Value, error) {
 	t.Helper()
 	forms, err := sexpr.ReadAll(src)
 	if err != nil {
 		t.Fatalf("ReadAll(%q): %v", src, err)
 	}
-	if len(forms) != 1 {
-		t.Fatalf("ReadAll(%q) returned %d forms, want 1", src, len(forms))
+	if len(forms) == 0 {
+		t.Fatalf("ReadAll(%q) returned no forms", src)
+	}
+	top := NewTopLevelIn(testEnv())
+	var v sexpr.Value
+	for _, f := range forms {
+		if v, err = top.Eval(f); err != nil {
+			return nil, err
+		}
 	}
-	return Eval(forms[0], testEnv())
+	return v, nil
 }
 
 type evalCase struct{ src, want string }
diff --git a/eval/function_test.go b/eval/function_test.go
index 983ba5de50b5f992fd1b1158061715741e7981ac..f8b5a872a2eff01eaa5bea6e19269a32be440c08 100644
--- a/eval/function_test.go
+++ b/eval/function_test.go
@@ -13,7 +13,8 @@ 	sexpr.FunctionBase
 	name string
 }
 
-func (f stubFunc) Name() string { return f.name }
+func (f stubFunc) Builtin() bool { return true }
+func (f stubFunc) Name() string  { return f.name }
 
 func TestEvalCanDefineFunctions(t *testing.T) {
 	var v sexpr.Value = stubFunc{name: "+"}
diff --git a/sexpr/print.go b/sexpr/print.go
index ee63d41d751c5857759453637a99c3df4e01cbcb..d5ade3f9fcb82d0fc802bfc1389fb69c8f0fbe29 100644
--- a/sexpr/print.go
+++ b/sexpr/print.go
@@ -36,9 +36,12 @@ 		b.WriteString("()")
 	case *Pair:
 		writePair(b, v)
 	case Function:
-		if name := v.Name(); name != "" {
-			fmt.Fprintf(b, "#<builtin %s>", name)
-		} else {
+		switch {
+		case v.Builtin():
+			fmt.Fprintf(b, "#<builtin %s>", v.Name())
+		case v.Name() != "":
+			fmt.Fprintf(b, "#<lambda %s>", v.Name())
+		default:
 			b.WriteString("#<lambda>")
 		}
 	default:
diff --git a/sexpr/print_test.go b/sexpr/print_test.go
index 59e409506d9f111a01ee7b27b223d1a04410eb38..0837fdd513fd47c97d90bd070bf74778ca95c61c 100644
--- a/sexpr/print_test.go
+++ b/sexpr/print_test.go
@@ -7,10 +7,12 @@ )
 
 type testFunc struct {
 	FunctionBase
-	name string
+	builtin bool
+	name    string
 }
 
-func (f testFunc) Name() string { return f.name }
+func (f testFunc) Builtin() bool { return f.builtin }
+func (f testFunc) Name() string  { return f.name }
 
 func TestPrint(t *testing.T) {
 	tests := []struct {
@@ -55,7 +57,8 @@ 		{"improper list", ListWithTail(Int(3), Int(1), Int(2)), "(1 2 . 3)"},
 		{"pair of lists", Cons(List(Int(1)), List(Int(2))), "((1) 2)"},
 		{"dotted to symbol", Cons(Symbol("a"), Symbol("b")), "(a . b)"},
 		{"quote form", List(Symbol("quote"), Symbol("x")), "(quote x)"},
-		{"builtin", testFunc{name: "+"}, "#<builtin +>"},
+		{"builtin", testFunc{builtin: true, name: "+"}, "#<builtin +>"},
+		{"named closure", testFunc{name: "fact"}, "#<lambda fact>"},
 		{"closure", testFunc{}, "#<lambda>"},
 	}
 	for _, tt := range tests {
diff --git a/sexpr/value.go b/sexpr/value.go
index d5b4d7de114db71643f85a44541c1ffc03c00dde..ad36655e7b5427c5dcf50cdd23f45e7c4c6f67cf 100644
--- a/sexpr/value.go
+++ b/sexpr/value.go
@@ -41,7 +41,9 @@ // Function is a callable value: a closure or a builtin, both defined in
 // package eval.
 type Function interface {
 	Value
-	// Name is the builtin's name, or "" for a closure.
+	Builtin() bool
+	// Name is a builtin's name, the name a closure was first defined
+	// under, or "" for an anonymous closure.
 	Name() string
 }