I'm going to explain this with the substitution model. The idea is that you can replace a variable with it's definition and substitute a procedure application with the expression in the body of the procedure and the formal perameters are expanded to it's aguments. Eg.:
(define square (lambda (x) (* x x)))
(square 5)
So we start with (sqrt 5)
since it starts the processs (not a definition)
(square 5) ; ==> subst square
((lambda (x) (* x x)) 5) ; ==> apply x=5
(* 5 5) ; ==> 25
Now let's do the same with your example:
(define f (lambda (g) (lambda (x) (g (+ (g x) (g x)))))) (define e (lambda (x) (* x 3))) (define d (f e)) (d 4)
Or we could just start with d
since it's definition is an expression (f e)
:
(f e) ; subs f ==>
((lambda (g) (lambda (x) (g (+ (g x) (g x))))) e) ; apply g=e ==>
(lambda (x) (e (+ (e x) (e x)))) ; subst first e ==>
(lambda (x) ((lambda (x) (* x 3)) (+ (e x) (e x)))) ; apply x=(+ (e x) (e x)) ==>
(lambda (x) (* (+ (e x) (e x)) 3)) ; subst e+apply x=x ==>
(lambda (x) (* (+ (* x 3) (* x 3)) 3)) ; now this is d
So in reality f
and e
is now irrelevant since by substitution rules you could have written (define d (lambda (x) (* (+ (* x 3) (* x 3)) 3))
instead.
Then we do the (d 4)
using it's new definition:
(d 4) ; subst d ==>
((lambda (x) (* (+ (* x 3) (* x 3)) 3)) 4) ; apply x=4 ==>
(* (+ (* 4 3) (* 4 3)) 3) ; ==> 72
I've done this manually but you can do it automatically for simple Scheme code in DrRacket by choosing "Intermediate student" as language at the bottom left dropdown menu and press STEP >|. Your code has 13 steps. However, it helps to do it manually a couple of times to get the hang of it and you'll understand better after watching the SICP videoes and you'll be quite good if you finish the questions in the book. Book and videos are free so you only have to pay with your time to ace Scheme.