-
Notifications
You must be signed in to change notification settings - Fork 3
/
grotskyList.go
94 lines (86 loc) · 2.22 KB
/
grotskyList.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package internal
import (
"reflect"
)
type grotskyList []interface{}
func applyOpToList(op func(x, y []interface{}) interface{}, arguments ...interface{}) (interface{}, error) {
x := arguments[0].(grotskyList)
y, ok := arguments[1].(grotskyList)
if !ok {
return nil, errExpectedList
}
return op([]interface{}(x), []interface{}(y)), nil
}
var listBinaryOperations = map[operator]func(x, y []interface{}) interface{}{
opAdd: func(x, y []interface{}) interface{} {
return grotskyList(append(x, y...))
},
opSub: func(x, y []interface{}) interface{} {
temp := make(map[interface{}]bool)
for _, e := range x {
temp[e] = true
}
for _, e := range y {
if val, ok := temp[e]; ok && val {
temp[e] = false
}
}
out := make([]interface{}, 0)
for e, ok := range temp {
if ok {
out = append(out, e)
}
}
return grotskyList(out)
},
opEq: func(x, y []interface{}) interface{} {
return grotskyBool(reflect.ValueOf(x).Pointer() == reflect.ValueOf(y).Pointer())
},
opNeq: func(x, y []interface{}) interface{} {
return grotskyBool(reflect.ValueOf(x).Pointer() != reflect.ValueOf(y).Pointer())
},
}
func (l grotskyList) get(state *interpreterState, tk *token) interface{} {
if tk.lexeme == "length" {
return grotskyNumber(len(l))
}
state.runtimeErr(errUndefinedProp, tk)
return nil
}
func (l grotskyList) set(state *interpreterState, name *token, value interface{}) {
state.runtimeErr(errReadOnly, name)
}
func (l grotskyList) getOperator(op operator) (operatorApply, error) {
if apply, ok := listBinaryOperations[op]; ok {
return func(arguments ...interface{}) (interface{}, error) {
return applyOpToList(apply, append([]interface{}{l}, arguments...)...)
}, nil
}
if op == opNeg {
// return unique elements
return func(arguments ...interface{}) (interface{}, error) {
temp := make(map[interface{}]bool)
for _, e := range l {
temp[e] = true
}
out := make([]interface{}, 0)
for e := range temp {
out = append(out, e)
}
return grotskyList(out), nil
}, nil
}
return nil, errUndefinedOp
}
func (l grotskyList) String() string {
out := "["
i := 0
for _, val := range l {
out += printObj(val)
if len(l) > 1 && i != len(l)-1 {
out += ", "
}
i++
}
return out + "]"
}