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.

Procedures have first-class status in Scheme.

- They may be named by variables.
- They may be passed as arguments to procedures.
- They may be returned as the results of procedures.
- They may be included in data structures. (We'll see examples of this once we see some data structures, but not today.)

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

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

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

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

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

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

And use(define square (make-expt 2))

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

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

Use prod to calculate the product for i=1 to 10 of 1/i.(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=2 to 100 (i even) for i^2.(prod (lambda (x) (/ 1 x)) 1 (lambda (x) (+ 1 x)) 10)

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

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

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

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

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

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

(procedure-with-let 4)

=> 18

Last update: October 2000