-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteger.go
More file actions
102 lines (92 loc) · 2.15 KB
/
integer.go
File metadata and controls
102 lines (92 loc) · 2.15 KB
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
package gmnlisp
import (
"context"
"fmt"
"math/big"
)
type Integer int64
var integerClass = registerClass(&BuiltInClass{
name: NewSymbol("<integer>"),
instanceP: func(n Node) bool {
if _, ok := n.(Integer); ok {
return true
}
_, ok := n.(BigInt)
return ok
},
create: func() Node { return Integer(0) },
super: []Class{ObjectClass, numberClass},
})
func (i Integer) ClassOf() Class {
return integerClass
}
func (i Integer) String() string {
return fmt.Sprintf("%d", int64(i))
}
func (i Integer) Equals(n Node, m EqlMode) bool {
if m == EQUALP {
if _n, ok := n.(Integer); ok && i == _n {
return true
}
_n, ok := n.(Float)
return ok && Float(i) == _n
} else {
_n, ok := n.(Integer)
return ok && i == _n
}
}
func (i Integer) Add(ctx context.Context, w *World, n Node) (Node, error) {
if _n, ok := n.(Float); ok {
return Float(i) + _n, nil
}
_n, err := ExpectClass[Integer](ctx, w, n)
if err == nil {
return i + _n, nil
}
return nil, err
}
func (i Integer) Sub(ctx context.Context, w *World, n Node) (Node, error) {
return promoteOperands(ctx, w, i, n,
func(a, b Integer) (Node, error) {
return a - b, nil
},
func(a, b BigInt) (Node, error) {
return BigInt{Int: new(big.Int).Sub(a.Int, b.Int)}, nil
},
func(a, b Float) (Node, error) {
return a - b, nil
},
func(a, b *big.Float) (Node, error) {
v, _ := new(big.Float).Sub(a, b).Float64()
return Float(v), nil
})
}
func (i Integer) Multi(ctx context.Context, w *World, n Node) (Node, error) {
if _n, ok := n.(BigInt); ok {
return _n.Multi(ctx, w, i)
} else if _n, ok := n.(Float); ok {
return Float(i) * _n, nil
}
_n, err := ExpectClass[Integer](ctx, w, n)
if err != nil {
return nil, err
}
r := i * _n
if _n != 0 && r/_n != i { // overflow
return BigInt{Int: big.NewInt(int64(i))}.Multi(ctx, w, _n)
}
return r, nil
}
func (i Integer) LessThan(ctx context.Context, w *World, n Node) (bool, error) {
if v, ok := n.(BigInt); ok {
return big.NewInt(int64(i)).Cmp(v.Int) < 0, nil
}
if _n, ok := n.(Float); ok {
return Float(i) < _n, nil
}
_n, err := ExpectClass[Integer](ctx, w, n)
if err == nil {
return i < _n, nil
}
return false, err
}