-
Notifications
You must be signed in to change notification settings - Fork 1
/
env.go
51 lines (44 loc) · 963 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
package common
type Env[K comparable, V any] struct {
parent *Env[K, V]
bindings map[K]V
}
func NewEnv[K comparable, V any](parent *Env[K, V]) *Env[K, V] {
return &Env[K, V]{
parent: parent,
bindings: map[K]V{},
}
}
func zero[V any]() V {
var result V
return result
}
func (env Env[K, V]) LookUp(key K) (V, bool) {
if v, ok := env.bindings[key]; ok {
return v, ok
} else if env.parent != nil {
return env.parent.LookUp(key)
} else {
return zero[V](), false
}
}
func (env Env[K, V]) Add(key K, value V) {
env.bindings[key] = value
}
// Contain returns whether the key occurs at the current level.
func (env Env[K, V]) Contain(key K) bool {
_, existed := env.bindings[key]
return existed
}
func (env Env[K, V]) Keys() map[K]bool {
var keys map[K]bool
if env.parent != nil {
keys = env.parent.Keys()
} else {
keys = make(map[K]bool, len(env.bindings))
}
for key := range env.bindings {
keys[key] = true
}
return keys
}