-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr.go
74 lines (60 loc) · 1.07 KB
/
expr.go
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
package main
import (
"fmt"
)
type expr interface {
eval(e *env) (val, error)
}
type symexpr struct {
expr string
}
func (s *symexpr) eval(e *env) (val, error) {
if s == nil {
return nil, fmt.Errorf("symexpr is nil")
}
return e.lookup(s)
}
type intexpr struct {
expr int
}
func (i *intexpr) eval(e *env) (val, error) {
if i == nil {
return nil, fmt.Errorf("intexpr is nil")
}
return &intval{i.expr}, nil
}
type strexpr struct {
expr string
}
func (s *strexpr) eval(e *env) (val, error) {
if s == nil {
return nil, fmt.Errorf("strexpr is nil")
}
return &strval{s.expr}, nil
}
type sexpr []expr
func (se sexpr) eval(e *env) (val, error) {
if len(se) > 0 {
if s, ok := (se[0]).(*symexpr); ok {
switch s.expr {
case "lambda":
return lambda(se[1:], e)
case "defvar":
return defVar(se[1:], e)
}
}
}
var vals listval
for _, expr := range se {
val, err := expr.eval(e)
if err != nil {
return nil, err
}
vals = append(vals, val)
}
if f, ok := (vals[0]).(*funcval); ok {
// apply
return f.val(vals[1:])
}
return vals, nil
}