Procedures As Arguments
Suppose we want a procedure called
arithmetic to take three arguments: an
arithmetic operator and two operands:
(arithmetic + 3 4) ⇒ 7
(arithmetic * 3 4) ⇒ 12
(arithmetic remainder 30 4) ⇒ 2
One way:
(define arithmetic
(lambda (operate op1 op2)
(cond ((equal? operate +) (+ op1 op2))
((equal? operate *) (* op1 op2))
((equal? operate remainder) (remainder op1 op2)))))
- arithmetic takes an arithmetic operator as an argument,
so it is a higher-order procedure.
- equal? is a more general equality predicate than
=, which works only on numbers.
- This use of equal? has a procedure as its second
argument, so equal? is also a higher-order procedure.
Q: Why is arithmetic
inconvenient?