Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

SICP

Name: Anonymous 2010-07-17 14:31

I'm having trouble visualizing the processed produced by the examples provided in exercise 1.9.

In case you've forgotten or are not familiar I've included the problem: http://pastebin.com/7PYmxrSS

Whenever I expand these recursive procedures I always end up getting an iterative process, so I don't believe I'm doing it correctly.
Any tips or tricks to help would be greatly appreciated.

Name: Anonymous 2010-07-17 14:47

I'm not sure why how you manage to get an iterative process for the first one, but if you are having trouble just draw it out and remember to evaluate your arguments before the applying the procedure
(define (+ a b)
  (if (= a 0)
  b
  (inc (+ (dec a) b))))
(+ 3 4)
(inc (+ (dec 3) 4))
(inc (+ 2 4))
(inc (inc (+ (dec 2) 4)))
(inc (inc (+ 1 4)))
(inc (inc (inc (+ (dec 1) 4))))
(inc (inc (inc (+ 0 4))))
(inc (inc (inc 4)))
(inc (inc 5))
(inc 6)
7

Name: Anonymous 2010-07-17 14:55

>>1
The first is recursive, the second is iterative.

First:

(+ 2 3) = (1+ (+ 1 3)) = (1+ (1+ (+ 0 3))) = (1+ (1+ 3)) = (1+ 4) = 5


Second:

(+ 2 3) = (+ 1 4) = (+ 0 5) = 5


See the difference? In one case, a form generates calls to itself recursively (the result of the plus call is recursive so it's needed), in the other a form is substituted with itself directly.

To better clarify why the second one isn't recursive:
Scheme can perform TCO (tail call optimization), which means that in the second case, since the call to itself is the last form, the value will be implicitly returned and you can expect the function to return the value returned by the inner call, so the call can be turned into a jump, thus the second one is just an iterative process. In the first case, the result of the recursive call is used further (to increment), so TCO cannot be performed, so the functions remains recursive (unlike the second, where it does not).

It's been a while since I read my SICP, so I don't know if they talk about TCO so early, but that's the gist of it (first being normal recursion where the result is used further, and second being iteration as emulated by recursive calls, but the actual process is iterative as the value is returned directly from the called function as the return value of the caller function). The substitution model also better illustrates how the recursive model grows(it grows the stack), while the iterative one doesn't grow (the stack).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List