I was wondering how do you implement a tail-resursive power function in scheme?
I've got my recursive one defined for scheme:
(define power-is-fun
(lambda (x y)
(cond [(= y 0)
1]
[(> y 0)
(* (power-is-fun x (- y 1)) x)])))
But I can't quite figure out how the other one is supposed to be.
The answer is similar, you just have to pass the accumulated result as a parameter:
(define power-is-fun
(lambda (x y acc)
(cond [(= y 0)
acc]
[(> y 0)
(power-is-fun x (- y 1) (* x acc))])))
Call it like this, notice that the initial value for acc
is 1
(you can build a helper function for this, so you don't have to remember to pass the 1
every time):
(power-is-fun 2 3 1)
> 8
Some general pointers to transform a recursive procedure to a tail-recursion:
power-is-fun
, whereas in the tail-recursive version, the call to power-is-fun
is the last thing that happens before exiting the procedureIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With