Recursion is slowing me down immensely in my learning of Common Lisp. Recursion is simple, but I have a hard time visualizing the cycle flow. I tried drawing flow charts, but flow charts don't visualize accumulation very well. For me, it seems that evaluation code flow works best for understanding recursion. I think I got most of the recursion templates down, but the multiple/tree recursion is still wracking my brain. Here is the infamous code for the Fibonacci number:
(fibo 5)
(+ (fibo 4) (fibo 3))
(+ (+ (fibo 3) (fibo 2)) (+ (fibo 2) (fibo 1)))
(+ (+ (+ (fibo 2) 1) (+ (fibo 1) 1)) (+ (+ (fibo 1) 1) 1))
...
(+ (+ (+ (+ 1 1) 1) (+ 1 1)) (+ (+ 1 1) 1))
(+ (+ (+ 2 1) 2) (+ 2 1))
(+ (+ 3 2) 3)
...
8
I think my evaluation code is probably disorganized, but I would just be happy that my basic assumption is confirmed.
(defun fibo (n)
(cond ((equal n 0) 1)
((equal n 1) 1)
(t (+ (fibo (- n 1)) (fibo (- n 2))))))
I am trying to figure out how lisp evaluates this program one cycle at a time and this is what I think happens:(fibo 5)
(+ (fibo 4) (fibo 3))
(+ (+ (fibo 3) (fibo 2)) (+ (fibo 2) (fibo 1)))
(+ (+ (+ (fibo 2) 1) (+ (fibo 1) 1)) (+ (+ (fibo 1) 1) 1))
...
(+ (+ (+ (+ 1 1) 1) (+ 1 1)) (+ (+ 1 1) 1))
(+ (+ (+ 2 1) 2) (+ 2 1))
(+ (+ 3 2) 3)
...
8
I think my evaluation code is probably disorganized, but I would just be happy that my basic assumption is confirmed.
Last edited by speech impediment on , edited 1 time in total.