diff options
Diffstat (limited to 'subex/arithmetic.go')
-rw-r--r-- | subex/arithmetic.go | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/subex/arithmetic.go b/subex/arithmetic.go index 7200ac7..5497a68 100644 --- a/subex/arithmetic.go +++ b/subex/arithmetic.go @@ -85,3 +85,36 @@ func multiplyValues(atoms []walk.Atom) ([]walk.Atom, error) { return []walk.Atom{walk.ValueNumber(product)}, nil } } + +// Does tries to cast all to numbers and negates them +func negateValues(atoms []walk.Atom) ([]walk.Atom, error) { + var negatedNumbers []walk.Atom + values, err := walk.MemoryCompound(atoms) + if err != nil { + return nil, err + } + for _, value := range values { + switch v := value.(type) { + case walk.ValueNull: + negatedNumbers = append(negatedNumbers, walk.ValueNumber(0)) + case walk.ValueBool: + if bool(v) { + negatedNumbers = append(negatedNumbers, walk.ValueNumber(-1)) + } else { + negatedNumbers = append(negatedNumbers, walk.ValueNumber(0)) + } + case walk.ValueNumber: + negatedNumbers = append(negatedNumbers, walk.ValueNumber(-v)) + case walk.ValueString: + num, err := strconv.ParseFloat(string(v), 64) + if err == nil { + negatedNumbers = append(negatedNumbers, walk.ValueNumber(-num)) + } else { + return nil, errors.New("Tried to sum non-castable string") + } + default: + return nil, errors.New("Tried to sum non-number") + } + } + return negatedNumbers, nil +} |