Arc Forumnew | comments | leaders | submitlogin
1 point by globalrev 6063 days ago | link | parent

is it possible to do a tail-recursive power-function? would it then be faster than both or still slower than the normal recursive function?


3 points by sacado 6063 days ago | link

Not tested, but it should work and is tail-recursive :

  (def power (nbr pow res)
    (if (is pow 0)
	    res
        (> pow 0)
            (power nbr (- pow 1) (* nbr res))
	(< pow 0)
            (power nbr (* -1 pow) (/ 1 res))))
Not sure for the case where (< pow 0), though. Just run the tests, but I think the tail-recursive function is at least as fast as the iterative one. Actually, in fine, iterative code is transformed into its tail-recursive equivalent : code involving for is transformed as a bunch of tail-recursive functions for example.

-----