Search code examples
functional-programmingschemelispracketsicp

In this concrete case, how is "trace" supposed to work in Racket?


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?


Solution

  • 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.