do you think the factorial can benefit from a `tai...
# announcements
e
do you think the factorial can benefit from a
tailrect
function?
Copy code
var result = 1
for (i in 1..a)
    result *= i
result
🚫 1
m
Yess! For factorial No! Because we don't need to implement it as recursive. using tail-rec reduces memory usage of stack(comparing traditional recursive). To implement it in tail-rec, the method call should be return statement
👍 1
e
yes or no, then?
m
Not for factorial. I was wrong at first
actually, it will be the same, with or without tail-rec
If your question is that can we? yes, we can use. But, if your question is it better to use tail-rec? the answer is no preferences
👍 1
m
Well, you can implement factorial as a tail recursive function too, but it will overflow the
Long
so quickly that it doesn't make that much sense to do it. You cannot get a
StackOverflowException
with it though.
Copy code
fun factorial(n: Long): Long {
    tailrec fun fact(acc: Long, curr: Long): Long = 
        if (curr == 1L) acc
        else fact(acc * curr, curr - 1L)
    
    return fact(1, n)
}
👍 1
s
could always just use
reduce
instead, like
(1..a).reduce { product, next -> product * next }