angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
422 stars 58 forks source link

lessThanOrEquals #83

Open nikitabobko opened 2 years ago

nikitabobko commented 2 years ago
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