ArsDigita University, Structure and Interpretation of Computer Programs

Lecture Notes for Lecture 3 -- October 2000

Topics covered in today's lecture:

The code for this lecture is called higher-order-procs.scm. This file may be run if you wish to experiment with the code from the lecture.

Higher Order Procedures

Higher-order procedures are procedures that manipulate other procedures.

Procedures have first-class status in Scheme.

Summing


(define sum
   (lambda (term a next b)
      (if (> a b)
          0
          (+ (term a)
             (sum term
                  (next a)
                  next
                  b)))))
To compute the sum for i=1 to n of i, we write

(sum (lambda (x) (x))
     1
     (lambda (x) (+ x 1))
     n)
How do we compute the sum for i=1 to n of 1/i)?

(sum (lambda (x) (/ 1 x))
     1
     (lambda (x) (+ 1 x))
     n)
How about the sum for i=1 to n of i^3+2i?

(sum (lambda (x) (+ (* x x x) (* 2 x)))
     1
     (lambda (x) (+ 1 x))
     n)

Procedures that return procedures

Here is a procedure for exponentiation:

(define expt
   (lambda (b n)
      (if (= n 0)
          1
          (* b (expt b (- n 1))))))
How could we use this procedure to allow us to create procedures to calculate n^2, n^3, n^4, etc?

(define make-expt
   (lambda (n)
      (lambda (b) (expt b n))))
Now, let's use the make-expt procedure we just wrote to define square.

(define square
   (make-expt 2))
And use make-expt to write cube:

(define cube
   (make-expt 3))
How do we define a procedure to return n^8?

(define power-8
   (make-expt 8))

Multiplying: A Different Take on Sum

Let's write a procedure to compute the product for i=1 to n of f(n). Note the similarity to the sum procedure above.

(define prod
   (lambda (term a next b)
      (if (> a b)
          1
          (* (term a)
             (prod term
                   (next a)
                   next
                   b)))))
Use prod to calculate the product for i=1 to 10 of 1/i.

(prod (lambda (x) (/ 1 x))
     1
     (lambda (x) (+ 1 x))
     10)
Use prod to calculate the product for i=2 to 100 (i even) for i^2.

(prod (lambda (x) (* x x))
     2
     (lambda (x) (+ 2 x))
     100)

Let there be local variables

The general format of the let statement is

(let ((<var1> <exp1>)
      (<var2> <exp2>)
      ...
      (<varn> <expn>))
  <body>)
The let statement is equivalent to the following

((lambda (<var1> <var2> ... <varn>)
     <body>)
 <exp1>
 <exp2>
 ... 
 <expn>)
For example,

(let ((a 2)
      (b 3) 
      (c 4))
   (+ a b c))
de-sugars into

((lambda (a b c) (+ a b c)) 2 3 4)
which would return 9.

(define procedure-with-let
   (lambda (x)
      (let ((a (+ x 2))
            (b (* x 3)))
         (+ a b))))
What will be returned by the following call?

(procedure-with-let 4)

=>  18



Last update: October 2000