support nil value to compare
please run the example code below:
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
env := map[string]any{}
tests := []struct{ code string }{
{`key == "str"`}, // ok
{`key >= "str"`}, // invalid operation: <nil> >= string
{`key > "str"`}, // invalid operation: <nil> > string
{`key <= "str"`}, // invalid operation: <nil> <= string
{`key < "str"`}, // invalid operation: <nil> < string
}
for _, tt := range tests {
program, _ := expr.Compile(tt.code)
output, err := expr.Run(program, env)
fmt.Println(output, err)
}
}
can Expr support >、>=、<、<= like == operator? tks~
@antonmedv any ideas? tks~
Well, I 'm now sure if we should add such a feature.
- Case with
nil == nilis easy and trivial. - But for
nil >= nil, what should we do? Andnil <= nil? How it will affect sorting? - For reference: Python does not allow for >= with None:
>>> None >= None Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>=' not supported between instances of 'NoneType' and 'NoneType'
I agree with your point about comparing nil with nil. However, regarding comparisons between nil and specific values (like nil > 1), would it be possible for expr to support this to provide a better user experience? Thank you.
Interesting topic! I have a lot of math with potential nil values in my application and implemented the logic with a patcher. But I think expected results will be application dependent: is nil > 1 false, or nil? To me, nil is not comparable to any value, so nil > nil is false. To be consistent, nil == nil would be false as well!
@mdmcconnell has a good point.
I think it is better to be explicit:
(nil ?? 0) > 1
(nil ?? 999) > 1