Middle Earth

sicp-exercise-1.40-1.43

Exercise 1.40

I think this exercise is just to let me write a procedure returning another procedure, right?
cubic takes three parameters as those coefficients, and returns a procedure which takes one parameter.

(define (cubic a b c)
(lambda (x) (+ (cube x)
(* a (square x))
(* b x)
c)))

Exercise 1.41


(define (double f)
(lambda (x) (f (f x))))

The value of (((double (double double)) inc) 5) is 21.
This is how I analyze it,
(double (double double)) will perform as, (yes, it’s like normal order evaluation, but they say the results are the same with normal and applicative)
((double double) (double double))
(double double) means applying four times; in the expression above, the second (double double), as operand, applies inc four times, and the first (double double) applies this four-times-inc four times. So adding 16 to 5, generating 21.

Exercise 1.42

(define (compose f g) (lambda (x) (f (g x))))

Exercise 1.43


(define (repeated func times)
(define (nth-repeat result n)
(if (= n 1)
result
(nth-repeat (compose func result)
(- n 1))))
(nth-repeat func times))

My first attemp not using the hint:

(define (repeated func times)
(define (nth-repeat result n)
(if (= n 1)
result
(nth-repeat (lambda (x)
(func (result x)))
(- n 1))
(nth-repeat func times))))

I forgot about the hint, so it takes me some time here,previously I get this error:
;The object #[compound-procedure 1 inc], passed as the first argument to integer-add, is not the correct type.
–Because I wrote things like (nth-repeat (func result))
but, it’s in fact not hard, since the func always takes one argument, which of course shouldn’t be a procedure; I must apply (result x) first, and supply its result to func.
The lesson is, abstraction can help, at least make it easier to think clear.

Comments