Skip to content

support nil value to compare #755

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
5idu opened this issue Feb 20, 2025 · 5 comments
Open

support nil value to compare #755

5idu opened this issue Feb 20, 2025 · 5 comments
Labels

Comments

@5idu
Copy link

5idu commented Feb 20, 2025

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
Copy link
Author

5idu commented Feb 24, 2025

@antonmedv any ideas? tks~

@antonmedv
Copy link
Member

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'
    

@5idu
Copy link
Author

5idu commented Feb 25, 2025

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.

@mdmcconnell
Copy link
Contributor

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!

@antonmedv
Copy link
Member

@mdmcconnell has a good point.

I think it is better to be explicit:

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

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants