5

I am using the famous book SICP. On the exercise 1.18 a strange thing happens.

I wrote this code:

(define (double n) (* 2 n)) 
(define (halve n) (/ n 2))
(define (fast-mult a b)
    (fast-mult-iter a b 0))
(define (fast-mult-iter a b counter)
    (cond ((= b 0) counter)
          ((even? b) (fast-mult-iter (double a) (halve b) counter))
          (else (fast-mult-iter a (- b 1) (+ a counter)))))

I was using the "trace" function.

 (require racket/trace)
 (trace fast-mult)

I thought this "trace" would show me all steps the function follows until the final output. Hence, I thought that after calling

(fast-mult 4 3)

I would get:

>  (fast-mult-iter 4 3 0)
>  (fast-mult-iter 4 2 4)
>  (fast-mult-iter 8 1 4)
>  (fast-mult-iter 8 0 12)
< 12

However, what happens is that I get the following:

>  (fast-mult-iter 4 3)
< 12

Why does this happen? Did I misunderstand how trace works in Racket?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Why someone gave me a downvote? Is my question bad? –  Aug 25 '16 at 20:52
  • Meh, it's probably just someone not liking the way you asked the question. I wouldn't think too much of it as it's a more or less fine question. – Leif Andersen Aug 25 '16 at 21:56

1 Answers1

8

You're very close. The reason why trace is not giving you the result you expect is because you only traced fast-mult, and not fast-mult-iter. If you modify your trace line to be:

(trace fast-mult fast-mult-iter)

Then the result you get is:

>(fast-mult 4 3)
>(fast-mult-iter 4 3 0)
>(fast-mult-iter 4 2 4)
>(fast-mult-iter 8 1 4)
>(fast-mult-iter 8 0 12)
<12

Which is the answer you expect.

Leif Andersen
  • 21,580
  • 20
  • 67
  • 100