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
elect
05/21/2020, 1:40 PM
yes or no, then?
m
Mohsen Kashi
05/21/2020, 1:41 PM
Not for factorial. I was wrong at first
Mohsen Kashi
05/21/2020, 1:42 PM
actually, it will be the same, with or without tail-rec
Mohsen Kashi
05/21/2020, 1:44 PM
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
marstran
05/21/2020, 6:15 PM
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)
}