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.
(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)
(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))
(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 ((<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