-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcomplex.go
More file actions
91 lines (76 loc) · 2.1 KB
/
complex.go
File metadata and controls
91 lines (76 loc) · 2.1 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
// Copyright (c) 2022, Peter Ohler, All rights reserved.
package slip
import (
"strconv"
)
// ComplexSymbol is the symbol with a value of "complex".
const ComplexSymbol = Symbol("complex")
// Complex is a numerator and denominator pair.
type Complex complex128
// String representation of the Object.
func (obj Complex) String() string {
return string(obj.Append([]byte{}))
}
// Append a buffer with a representation of the Object.
func (obj Complex) Append(b []byte) []byte {
b = append(b, "#C("...)
b = printer.Append(b, DoubleFloat(real(obj)), 0)
b = append(b, ' ')
b = printer.Append(b, DoubleFloat(imag(obj)), 0)
return append(b, ')')
}
// Simplify the Object into an int64.
func (obj Complex) Simplify() any {
var b []byte
b = strconv.AppendInt(b, int64(real(obj)), 10)
i := int64(imag(obj))
if 0 <= i {
b = append(b, '+')
}
b = strconv.AppendInt(b, i, 10)
b = append(b, 'i')
return string(b)
}
// Equal returns true if this Object and the other are equal in value.
func (obj Complex) Equal(other Object) (eq bool) {
if to, ok := other.(Complex); ok && complex128(obj) == complex128(to) {
eq = true
}
return
}
// Hierarchy returns the class hierarchy as symbols for the instance.
func (obj Complex) Hierarchy() []Symbol {
return []Symbol{ComplexSymbol, NumberSymbol, TrueSymbol}
}
// NumberType returns 'complex.
func (obj Complex) NumberType() Symbol {
return ComplexSymbol
}
// Eval returns self.
func (obj Complex) Eval(s *Scope, depth int) Object {
return obj
}
func newComplex(list List) Complex {
if len(list) != 2 {
ParsePanic(NewScope(), 0, "Can not forms a complex object from %s.", list)
}
var (
r float64
i float64
)
if rv, ok := list[0].(Real); ok {
r = rv.RealValue()
} else {
ParsePanic(NewScope(), 0, "Can not convert %s, a %T into a float.", list[0], list[0])
}
if rv, ok := list[1].(Real); ok {
i = rv.RealValue()
} else {
ParsePanic(NewScope(), 0, "Can not convert %s, a %T into a float.", list[1], list[1])
}
return Complex(complex(r, i))
}
// LoadForm returns a form that can be evaluated to create the object.
func (obj Complex) LoadForm() Object {
return obj
}