forked from erh/scheme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.go
113 lines (87 loc) · 1.81 KB
/
math.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package scheme
import (
"fmt"
)
var (
symbols = map[string]*Value{}
builtins = map[string]*Value{}
)
func init() {
symbols["+"] = &Value{Func: func(args []*Value, scope Scope) (*Value, error) {
total := 0.0
for _, a := range args {
n, err := a.ToFloat()
if err != nil {
return nil, err
}
total += n
}
return &Value{Float: &total}, nil
}}
symbols["*"] = &Value{Func: func(args []*Value, scope Scope) (*Value, error) {
total := 0.0
for idx, a := range args {
n, err := a.ToFloat()
if err != nil {
return nil, err
}
if idx == 0 {
total = n
} else {
total *= n
}
}
return &Value{Float: &total}, nil
}}
symbols["-"] = &Value{Func: func(args []*Value, scope Scope) (*Value, error) {
total := 0.0
for idx, a := range args {
n, err := a.ToFloat()
if err != nil {
return nil, err
}
if idx == 0 {
total = n
} else {
total = total - n
}
}
return &Value{Float: &total}, nil
}}
symbols["/"] = &Value{Func: func(args []*Value, scope Scope) (*Value, error) {
if len(args) != 2 {
return nil, fmt.Errorf("/ requres exactly 2 args")
}
a, err := args[0].ToFloat()
if err != nil {
return nil, err
}
b, err := args[1].ToFloat()
if err != nil {
return nil, err
}
if b == 0 {
return nil, fmt.Errorf("cannot divide by 0")
}
res := a / b
return &Value{Float: &res}, nil
}}
builtins["max"] = &Value{Func: func(args []*Value, scope Scope) (*Value, error) {
if len(args) == 0 {
return nil, fmt.Errorf("max needs at least 1 argument")
}
max := 0.0
for idx, a := range args {
n, err := a.ToFloat()
if err != nil {
return nil, fmt.Errorf("arg %d to max fail: %s", idx, err)
}
if idx == 0 {
max = n
} else if n > max {
max = n
}
}
return &Value{Float: &max}, nil
}}
}