Skip to content

Wrong solution to exercise 4.1 #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
sharubhat opened this issue Aug 21, 2023 · 0 comments
Open

Wrong solution to exercise 4.1 #22

sharubhat opened this issue Aug 21, 2023 · 0 comments

Comments

@sharubhat
Copy link

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))
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant