Search code examples
python-3.xsicp

Visualize the process of expand and contraction of recursion


I am practicing Exercise 1.17 of SICP

#+begin_src ipython :session alinbx :results output
def fast_mul(a, b):
    if b == 1: return a
    else:
        if even(b): return 2 * fast_mul(a, b//2)
        if odd(b):  return a  + 2 * fast_mul(a, b//2)
def even(n):
    return n % 2 == 0

def odd(n):
    return n % 2 == 1
print(fast_mul(3, 7))
#+end_src

#+RESULTS:
: 21

How could I see the process of expanding and contraction by adding print as

fast_mul(3,7)
3 + 2 * fast_mul(3, 3)
3 + 2 * (3 + 2 * fast_mul(3, 1))
3 + 2 * (3 + 2 * 3)
21

Solution

  • It sounds like you are looking for a trace, although the defaults may take some hacking to return the specific details you are looking for, eg.

    python -m trace -t fast_mul.py 
    

    In elisp, default tracing is closer to your desired output, eg.

    (defun fast-mul (a b)
      (if (eq 1 b) a
        (+ (if (evenp b) 0 a) (* 2 (fast-mul a (/ b 2))))))
    
    (trace-function 'fast-mul)
    (fast-mul 3 7)
    
    ;; 1 -> (fast-mul 3 7)
    ;; | 2 -> (fast-mul 3 3)
    ;; | | 3 -> (fast-mul 3 1)
    ;; | | 3 <- fast-mul: 3
    ;; | 2 <- fast-mul: 9
    ;; 1 <- fast-mul: 21