From 053a403a77e5b4c46e82932e94d5fb7a4117ce43 Mon Sep 17 00:00:00 2001 From: Charlie Stanton Date: Wed, 19 Apr 2023 12:41:10 +0100 Subject: Adjusts the sum operator to act as boolean OR when all inputs are booleans --- subex/subexstate.go | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'subex') diff --git a/subex/subexstate.go b/subex/subexstate.go index dbc8340..0a4f1bb 100644 --- a/subex/subexstate.go +++ b/subex/subexstate.go @@ -174,33 +174,43 @@ func (state SubexRangeState) accepting(store Store, outputStack OutputStack) []O return nil } -func sumValues(atoms []walk.Atom) (walk.ValueNumber, error) { +func sumValues(atoms []walk.Atom) (walk.WalkValue, error) { + allBools := true var sum float64 = 0 + var any bool = false values, err := walk.MemoryCompound(atoms) if err != nil { - return 0, err + return walk.ValueNull{}, err } for _, value := range values { switch v := value.(type) { case walk.ValueNull: + allBools = false case walk.ValueBool: if (bool(v)) { sum += 1 + any = true } case walk.ValueNumber: + allBools = false sum += float64(v) case walk.ValueString: + allBools = false num, err := strconv.ParseFloat(string(v), 64) if err == nil { sum += num } else { - return 0, errors.New("Tried to sum non-castable string") + return walk.ValueNull{}, errors.New("Tried to sum non-castable string") } default: - return 0, errors.New("Tried to sum non-number") + return walk.ValueNull{}, errors.New("Tried to sum non-number") } } - return walk.ValueNumber(sum), nil + if allBools { + return walk.ValueBool(any), nil + } else { + return walk.ValueNumber(sum), nil + } } // At the start of a sum, just pushes to the OutputStack allowing the end to capture what was output in the middle -- cgit v1.2.3