fpinkotlin icon indicating copy to clipboard operation
fpinkotlin copied to clipboard

Wrong solution to exercise 4.1

Open sharubhat opened this issue 2 years ago • 0 comments

The solution to add two numbers is incorrect and works purely by accident only because types of both inputs are Int. If one of them is changed to Long, the answers would be incorrect. Also very simple addition like add(3, -3) will result in a stackoverflow if the function is not marked tailrec because it takes 2^32 - 3 iterations to get b from -3 to 0.

Provided solution is tailrec fun add(x: Int, y: Int): Int = if (y == 0) x else add(inc(x), dec(y)). The correct solution would be

tailrec fun add(a: Int, b: Int): Int =
    when {
        (b == 0) -> a
        (b > 0) -> add(inc(a), dec(b))
        else -> add(dec(a), inc(b))
    }

sharubhat avatar Aug 21 '23 05:08 sharubhat