dave
dave

Reputation: 135

What am I doing wrong with this Scheme evaluation?

Evaluate:

((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5)

This is what I did:

And then I'm stuck.

Upvotes: 0

Views: 147

Answers (3)

leppie
leppie

Reputation: 117360

I suggest you break this down into individual 'defined' procedures.

(define part1 (lambda (y) (lambda (x) (+ x y)))) ; basically an adder
(define part2 (lambda (x) part1))  ; just return part1, x has no effect

Now call (((part2 3) 4) 5) => 9

Upvotes: 2

Matthias Benkard
Matthias Benkard

Reputation: 15769

-substitute 3 -> x in (lambda (y) (lambda (x) (+ x y))
-(lambda (y) (lambda (x) (+ 3 y))

First, this is wrong. You don't substitute 3 for all occurrences of x, only for the free ones. The x you're replacing here is bound by the inner lambda expression and therefore not free.

Second, there's nothing wrong with substituting a value for a variable that's never used, so substituting 5 for y in (+ 3 4) is fine and yields (+ 3 4).

Upvotes: 1

mweerden
mweerden

Reputation: 14061

Your first substitution is wrong; the x in (+ x y) is bound by the innermost lambda, not the outermost. This means the result of that substitution is just (lambda (y) (lambda (x) (+ x y))). The 3 is "lost". (Perhaps you should look up the substitution rules and apply them step by step to getter a better grasp of it.)

Regardless of this, to finish you can still apply (lambda (y) (7)) (or (lambda (y) (+ 4 x)) if you fix the above) to 5 to get 7 (or (+ 4 5) which evaluates to 9).

Upvotes: 1

Related Questions