Skip to content

Commit

Permalink
Small doc and code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Mar 13, 2019
1 parent dc0ba81 commit 0140f77
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 9 deletions.
5 changes: 3 additions & 2 deletions src/comparable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
# - `nil` if `self` and the other object are not comparable
#
# `Comparable` uses `<=>` to implement the conventional comparison operators
# (`<`, `<=`, `==`, `>=`, and `>`).
# (`<`, `<=`, `==`, `>=`, and `>`). All of these return `false` when `<=>`
# returns `nil`.
#
# Note that returning `nil` is only useful when defining a partial comparable
# relationship. One such example is float values: they are generally comparable,
# except for `NaN`. If none of the values of a type are comparable between each
# other, `Comparable` shouldn't be included.
#
# NOTE: when `nil` is returned from `<=>`, `Array#sort` and related sorting
# NOTE: When `nil` is returned from `<=>`, `Array#sort` and related sorting
# methods will perform slightly slower.
module Comparable(T)
# Compares this object to *other* based on the receiver’s `<=>` method,
Expand Down
4 changes: 1 addition & 3 deletions src/compiler/crystal/macros/methods.cr
Original file line number Diff line number Diff line change
Expand Up @@ -423,9 +423,7 @@ module Crystal
bool_bin_op(method, args) { |me, other| me <= other }
when "<=>"
num_bin_op(method, args) do |me, other|
v = me <=> other
return NilLiteral.new if v.nil?
v
(me <=> other) || (return NilLiteral.new)
end
when "+"
if args.empty?
Expand Down
2 changes: 1 addition & 1 deletion src/int.cr
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ struct Int
end
end

def <=>(other : Int)
def <=>(other : Int) : Int32
# Override Number#<=> because when comparing
# Int vs Int there's no way we can return `nil`
self > other ? 1 : (self < other ? -1 : 0)
Expand Down
9 changes: 6 additions & 3 deletions src/number.cr
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,12 @@ struct Number

# The comparison operator.
#
# Returns `-1`, `0` or `1` depending on whether `self` is less than *other*, equals *other*
# or is greater than *other*.
def <=>(other)
# Returns:
# - `-1` if `self` is less than *other*
# - `0` if `self` is equal to *other*
# - `-1` if `self` is greater than *other*
# - `nil` if self is `NaN` or *other* is `NaN`, because `NaN` values are not comparable
def <=>(other) : Int32?
# NaN can't be compared to other numbers
return nil if self.is_a?(Float) && self.nan?
return nil if other.is_a?(Float) && other.nan?
Expand Down

0 comments on commit 0140f77

Please sign in to comment.