public
Last active

  • Download Gist
TailRec.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
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.
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.