kotlin-puzzlers icon indicating copy to clipboard operation
kotlin-puzzlers copied to clipboard

lessThanOrEquals

Open nikitabobko opened this issue 2 years ago • 0 comments

fun main() {
    println((2.0..3.0).lessThanOrEquals(0.0, 1.0))
}

true, false, or compilation error?

After (or before) this puzzler the next puzzler may be shown:

fun main() {
    println((2..3).lessThanOrEquals(0, 1))
}

true, false, or compilation error?

Those two have different answers. The first one has the answer true because what lessThanOrEquals does is that it compares two arguments, not the ranges themselves. And the second puzzler is a compilation error.

Elaboration

lessThanOrEquals is only needed for floating point numbers to make it possible to implement coerceIn (1.0.coerceIn(1.0..2.0)) for floating point numbers. Inside coerceIn function we use lessThanOrEquals not compareTo because compareTo compares by total order but lessThanOrEquals compares according to IEEE.

You may observe total order vs IEEE comparison difference in this example:

fun main() {
    println(-0.0 == 0.0) // true. IEEE
    println(0.0.compareTo(-0.0) == 0) // false. Total Order
    // or try NaN :)
}

The credit also goes to https://github.com/ilya-g

nikitabobko avatar Aug 18 '22 11:08 nikitabobko