package object import ( "fmt" "math" ) // Float is the floating-point number type used to represent float literals and holds // an internal float64 value type Float struct { Value float64 } func (f Float) Bool() bool { return f.Value != 0 } func (f Float) Add(other Object) (Object, error) { switch obj := other.(type) { case Float: return Float{f.Value + obj.Value}, nil default: return nil, NewBinaryOpError(f, other, "+") } } func (f Float) Sub(other Object) (Object, error) { switch obj := other.(type) { case Float: return Float{f.Value - obj.Value}, nil default: return nil, NewBinaryOpError(f, other, "-") } } func (f Float) Mul(other Object) (Object, error) { switch obj := other.(type) { case Float: return Float{f.Value * obj.Value}, nil case String: return obj.Mul(f) case *Array: return obj.Mul(f) default: return nil, NewBinaryOpError(f, other, "*") } } func (f Float) Div(other Object) (Object, error) { switch obj := other.(type) { case Float: if obj.Value == 0 { return nil, NewDivisionByZeroError(f) } return Float{f.Value / obj.Value}, nil default: return nil, NewBinaryOpError(f, other, "/") } } func (f Float) Mod(other Object) (Object, error) { switch obj := other.(type) { case Float: return Float{math.Mod(f.Value, obj.Value)}, nil default: return nil, NewBinaryOpError(f, other, "%") } } func (f Float) LogicalNot() Object { return Boolean{!f.Bool()} } func (f Float) Negate() Object { return Float{-f.Value} } func (f Float) Compare(other Object) int { switch obj := other.(type) { case Float: if f.Value < obj.Value { return -1 } if f.Value > obj.Value { return 1 } return 0 default: return -1 } } func (f Float) String() string { return f.Inspect() } // Copy implements the Copyable interface func (i Float) Copy() Object { return Float{Value: i.Value} } // Hash implements the Hasher interface func (i Float) Hash() HashKey { return HashKey{Type: i.Type(), Value: uint64(i.Value)} } // Type returns the type of the object func (i Float) Type() Type { return FloatType } // Inspect returns a stringified version of the object for debugging func (i Float) Inspect() string { return fmt.Sprintf("%f", i.Value) }