Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

recursion problems

3 views
Skip to first unread message

Janzo

unread,
Mar 10, 2008, 8:48:20 AM3/10/08
to
I'm in troubles with a simple recursion

(define (sum x)
(if (= x 0)
0
(+ x (sum (- 1 x)))))

for the numbers 0 and 1 it works, but if I do (sum 2) the program
keeps thinking... and it doesn't do nothing. I'm using drscheme with
PLT, do you think it's problem of drscheme?

thanks.

Jussi Piitulainen

unread,
Mar 10, 2008, 9:06:00 AM3/10/08
to
Janzo <juanm...@gmail.com> writes:

You reduce (sum 2) to (+ 2 (sum -1)).

You reduce (sum -1) to (+ -1 (sum 2)).

You build a tower of pending additions (+ 2 (+ -1 (+ 2 ...))).

Janzo

unread,
Mar 10, 2008, 9:17:13 AM3/10/08
to
On Mar 10, 2:06 pm, Jussi Piitulainen <jpiit...@ling.helsinki.fi>
wrote:

> Janzo <juanman...@gmail.com> writes:
> > I'm in troubles with a simple recursion
>
> > (define (sum x)
> > (if (= x 0)
> > 0
> > (+ x (sum (- 1 x)))))
>
> > for the numbers 0 and 1 it works, but if I do (sum 2) the program
> > keeps thinking... and it doesn't do nothing. I'm using drscheme with
> > PLT, do you think it's problem of drscheme?
>
> You reduce (sum 2) to (+ 2 (sum -1)).
>
> You reduce (sum -1) to (+ -1 (sum 2)).
>

I didn't see that!
(- 1 x) != (- x 1) ,of course.
Thanks a lot.

0 new messages