-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Comparison.fromInt, make toInt a val, add PartialOrder comparison
- Loading branch information
Showing
4 changed files
with
59 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,30 @@ | ||
package cats.kernel | ||
|
||
/** ADT encoding the possible results of a comparison */ | ||
sealed abstract class Comparison extends Product with Serializable { | ||
/** The signum of this comparison */ | ||
def toInt: Int = this match { | ||
case Comparison.GreaterThan => 1 | ||
case Comparison.EqualTo => 0 | ||
case Comparison.LessThan => -1 | ||
} | ||
} | ||
sealed abstract class Comparison(val toInt: Int, val toDouble: Double) extends Product with Serializable | ||
|
||
object Comparison { | ||
final case object GreaterThan extends Comparison | ||
final case object EqualTo extends Comparison | ||
final case object LessThan extends Comparison | ||
final case object GreaterThan extends Comparison(1, 1.0) | ||
final case object EqualTo extends Comparison(0, 0.0) | ||
final case object LessThan extends Comparison(-1, -1.0) | ||
|
||
// Used for fromDouble | ||
private val SomeGt = Some(Comparison.GreaterThan) | ||
private val SomeEq = Some(Comparison.EqualTo) | ||
private val SomeLt = Some(Comparison.LessThan) | ||
|
||
def fromInt(int: Int): Comparison = { | ||
if (int > 0) Comparison.GreaterThan | ||
else if (int == 0) Comparison.EqualTo | ||
else Comparison.LessThan | ||
} | ||
|
||
def fromDouble(double: Double): Option[Comparison] = { | ||
if (double.isNaN) None | ||
else if (double > 0.0) SomeGt | ||
else if (double == 0.0) SomeEq | ||
else SomeLt | ||
} | ||
|
||
implicit val catsKernelEqForComparison: Eq[Comparison] = Eq.fromUniversalEquals | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters