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

1

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?

Nichy answered 25/8, 2016 at 20:47 Comment(2)
Why someone gave me a downvote? Is my question bad?Nichy
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.Fuchs
F
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.

Fuchs answered 25/8, 2016 at 21:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.