e

elect

05/21/2020, 1:01 PM
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

Mohsen Kashi

05/21/2020, 1:33 PM
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
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

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)
}``````
👍 1
s

serebit

05/21/2020, 10:44 PM
could always just use
``reduce``
instead, like
``(1..a).reduce { product, next -> product * next }``