Nothing to Teach

Exercise 1.4

SICP Exercise 1.4 (from PDF version of book)

Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:

(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))

When I first read this question, I was admittedly very confused by the syntax. So I started writing out my thoughts about it (classic rubber-ducking), and by the time I got to the end, it made sense!


To me it looks like it’s defining a procedure called “a-plus-abs-b” that takes two parameters: a and b.

So it sounds like the intention of this function is to do: a plus the absolute value of b.

When I look at the if statement, it starts out easy enough:

If b is greater than 0 return the + operator. Otherwise, return the - operator.

So depending on the outcome, you’ll ultimately end up with: (+ a b) or (- a b)

So again, given:

(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))

If I did: (a-plus-abs-b 2 3)

I’d get: ((if (> 3 0) + -) 2 3)

And since 3 is greater than 0, it would return the + operator. Leaving me with:

(+ 2 3)
5

Alternatively, if I did: (a-plus-abs-b 2 -3)

I’d get: ((if (> -3 0) + -) 2 -3)

And since -3 is not greater than 0, it would return the - operator. Leaving me with:

(- 2 -3)
(2 - (-3))
(2 + 3)
5
Tags: books sicp