Skip to content

Instantly share code, notes, and snippets.

@Blaisorblade
Last active December 17, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Blaisorblade/5672562 to your computer and use it in GitHub Desktop.
Save Blaisorblade/5672562 to your computer and use it in GitHub Desktop.
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