-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
56 lines (47 loc) · 916 Bytes
/
env.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
package main
import (
"fmt"
)
type env struct {
prior *env
m map[string]val
}
func stdEnv() *env {
return &env{
m: map[string]val{
"+": intPlus,
"*": intMultiply,
"-": intSubtract,
"/": intDivide,
"car": &funcval{car},
"cdr": &funcval{cdr},
},
}
}
func (e *env) add(s *symexpr, val val) error {
if e != nil && e.m != nil {
e.m[s.expr] = val
return nil
}
return fmt.Errorf("Invalid environment")
}
func (e *env) lookup(s *symexpr) (val, error) {
if e != nil && e.m != nil {
if val, ok := e.m[s.expr]; ok {
if val == nil {
return nil, fmt.Errorf("Value found in environment is nil : %v : %v", s.expr, e)
}
return val, nil
}
}
if e.prior != nil {
return e.prior.lookup(s)
}
return nil, fmt.Errorf("Value not found in environment : %v : %v", s.expr, e)
}
func (e *env) push() *env {
return &env{
prior: e,
m: map[string]val{},
}
}