Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Defining Comparable#!= #11227

Closed
HertzDevil opened this issue Sep 17, 2021 · 2 comments
Closed

Defining Comparable#!= #11227

HertzDevil opened this issue Sep 17, 2021 · 2 comments

Comments

@HertzDevil
Copy link
Contributor

Comparable overrides only 5 out of the 6 relational operators. The sole exception, #!=, will return true if the two operands are unordered, because it is effectively !(self == other):

x = Float64::NAN
y = {x}

# `Float64#!=` called
x <=> x # => nil
x != x  # => false

# `Object#!=` called
y <=> y # => nil
y != y  # => true

The results become consistent if the following is defined:

module Comparable(T)
  def !=(other : T) : Bool
    cmp = self <=> other
    cmp ? cmp != 0 : false
  end
end

# `Float64#!=` overrides `Comparable#!=`
x != x # => false

# `Comparable#!=` called
y != y # => false

Is there any reason this is not done in the standard library?

@straight-shoota
Copy link
Member

x != x #=> false is actually very surprising. The implementation of Float#!= seems to be missing a special case for NaN (which Float#== apparently covers).

I'd consider if there's even a good reason to override Object#!= at all. The default implementation !(self == other) is definitely correct.

The primary problem is that Float#!= is an override with wrong semantics.

@asterite
Copy link
Member

Is there any reason this is not done in the standard library?

I think Comparable#== was implemented before we allowed <=> to return nil, and != was totally overlooked (my fault!)

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

No branches or pull requests

3 participants