Last active
December 17, 2015 21:09
-
-
Save Blaisorblade/5672562 to your computer and use it in GitHub Desktop.
Answering to http://stackoverflow.com/a/6160080/53974.
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
import annotation.tailrec | |
object TailRec { | |
// A tail-recursive function, from | |
// http://stackoverflow.com/a/6160080/53974 | |
@tailrec def isDivis(x:Int, i:Int):Boolean = | |
if(i > 20) true | |
else if(x % i != 0) false | |
else isDivis(x, i+1) | |
// The same code, written using && and || (in a more readable way): | |
// since && and || are short-circuiting, this code means the same | |
// thing. So much the same that isDivis2 is also tail-recursive. | |
@tailrec def isDivis2(x: Int, i: Int): Boolean = | |
(i > 20) || (x % i == 0) && isDivis2(x, i+1) | |
// I compared the generated bytecode, and noticed that there is a | |
// minor difference - similar to the difference between if (cond) | |
// branch1 branch2 and if (!cond) branch2 branch1, that is the order | |
// of branches is different. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment