lispy.el demo 2: the substitution model for procedure application

Back to github This file in org-mode Function reference

Intro

Task summary

Understand how this code works:

(defun triangle-using-cond (number) (cond ((<= number 0) 0) ((= number 1) 1) ((> number 1) (+ number (triangle-using-cond (1- number)))))) 

I'll use The Substitution Model for Procedure Application from SICP.

Screencast

The screencast for this demo is here: https://www.youtube.com/watch?v=D7mK2q3yve4

Step-by-step expansion

step 1

Start with this code:

(defun triangle-using-cond (number) (cond ((<= number 0) 0) ((= number 1) 1) ((> number 1) (+ number (triangle-using-cond (1- number)))))) (triangle-using-cond 4) 

Eval the defun with e. Then do je to eval the next expression to get 10.

step 2

Press xfM to get:

(cond ((<= 4 0) 0) ((= 4 1) 1) ((> 4 1) (+ 4 (triangle-using-cond (1- 4))))) 

With e check that the result is still 10.

step 3

Evaluate the cond branches in your mind and simplify with qhrr.

(+ 4 (triangle-using-cond (1- 4))) 

Then ffxr.

(+ 4 (triangle-using-cond 3)) 

step 4

Press xfM again:

(+ 4 (cond ((<= 3 0) 0) ((= 3 1) 1) ((> 3 1) (+ 3 (triangle-using-cond (1- 3)))))) 

Evaluate the cond branches in your mind and simplify with qirr.

(+ 4 (+ 3 (triangle-using-cond (1- 3)))) 

Simplify further with ffxr.

(+ 4 (+ 3 (triangle-using-cond 2))) 

step 5

Press xfM again:

(+ 4 (+ 3 (cond ((<= 2 0) 0) ((= 2 1) 1) ((> 2 1) (+ 2 (triangle-using-cond (1- 2))))))) 

Evaluate the cond branches in your mind and simplify with qjrr.

(+ 4 (+ 3 (+ 2 (triangle-using-cond (1- 2))))) 

Simplify further with ffxr.

(+ 4 (+ 3 (+ 2 (triangle-using-cond 1)))) 

step 6

Press xfM again:

(+ 4 (+ 3 (+ 2 (cond ((<= 1 0) 0) ((= 1 1) 1) ((> 1 1) (+ 1 (triangle-using-cond (1- 1)))))))) 

Evaluate the cond branches in your mind and simplify with akrr.

(+ 4 (+ 3 (+ 2 1))) 

C-e e to check that the result is still 10. That's it.