expr icon indicating copy to clipboard operation
expr copied to clipboard

support nil value to compare

Open 5idu opened this issue 10 months ago • 5 comments

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~

5idu avatar Feb 20 '25 03:02 5idu

@antonmedv any ideas? tks~

5idu avatar Feb 24 '25 09:02 5idu

Well, I 'm now sure if we should add such a feature.

  • Case with nil == nil is easy and trivial.
  • But for nil >= nil, what should we do? And nil <= 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'
    

antonmedv avatar Feb 24 '25 10:02 antonmedv

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.

5idu avatar Feb 25 '25 02:02 5idu

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 avatar Feb 26 '25 12:02 mdmcconnell

@mdmcconnell has a good point.

I think it is better to be explicit:

(nil ?? 0) > 1
(nil ?? 999) > 1

antonmedv avatar Feb 26 '25 13:02 antonmedv