Lennon Day-Reynolds <> wrote in message news:<>.. .
> On Wed, 14 Jul 2004 21:57:20 +0900, Rainer Joswig
> <> wrote:
> > how should the PROD function mentioned in that authoritative
explanation
> > work? Looks not very convincing to me. M needs to be incremented
> > in the recursive call - otherwise it would be running for a very
> > LOOOOONG time. Obviously that example code has never been
> > checked.
> Tail-call elimination -- the recursive function will be optimized into
> a loop by the compiler.
>
> Lennon
Hmm
a) it can't be optimized because the function call is not a tail call
(unless the compiler does some other high-level transformations).
b) still some value needs to be changed. the thing just does not compute
a product in any useful way.
Say, if you want to compute a product from 1 to n, you need to
count somewhere. The function in the paper does not.
Here is the recursive version in Lisp:
(defun prod (m n f)
(if (= m n)
m
(* (funcall f m)
(prod (+ 1 m) n f))))
And here is a tail-recursive version:
(defun prod (m n f &optional (acc n))
(if (= m n)
acc
(prod (+ 1 m) n f
(* (funcall f m) acc))))
; product of numbers from 1 to 4
(prod 1 4 #'identity) -> 24