There is no tail call optimization. If you're going to implement factorial
in Julia, use a loop.

On Tue, Jan 26, 2016 at 1:33 PM, Sisyphuss <[email protected]> wrote:

>
>
> I wrote 3 versions of factorial: by recursion, by iteration, by for-loop
>
> rec_factorial(n) = n == one(n) ? one(n) : n * rec_factorial(n-1)
>
> function iter_factorial(n)
>   fact_iter(one(n),one(n),n)
> end
>
> function fact_iter(product, counter, max_count)
>   if counter > max_count
>     product
>   else
>     fact_iter(product * counter, counter + one(counter), max_count)
>   end
> end
>
> function myfactorial(n)
>   product = one(n)
>   for i = one(n):n
>     product *= i
>   end
>   product
> end
>
> Then I timed it:
> @timeit rec_factorial(10000)       # 28.84 µs
> @timeit iter_factorial(10000)      # 24.15 µs
> @timeit myfactorial(10000)         #  8.06 µs
> This result is robust.
>
> Now, the question is how to explain tis result:
> 1) why version 2 is slightly faster than version 1?
> 2) why version 3 is mush faster than the other 2? Has the tail call
> optimization really worked here?
>

Reply via email to