Other Common Higher-Order Procedures
If you think about other procedures you've written or read this semester,
you can probably identify a variety of other common patterns. Once
you've identified a pattern, you can think about turning that pattern
into a higher-order procedure. Here are a few worth thinking about.
Folding
In cases like sum and product,
we used a binary procedure (+ and *,
respectively) to combine all the values in a list. We typically
call the generalized version of such a procedure fold.
For example, (fold + (list 1 2 3 4)) describes
1+2+3+4. Once we've defined fold,
we can more easily define sum as
(define sum
(lambda (lst) (fold + lst)))
or even
(define sum (l-s fold +))
Tallying
We've also made it common practice to count all the values in a
list that meet some predicate (all the dark colors, all the odd
numbers, etc.). Traditionally, we call such counting
tallying
and call the generalized pattern
(tally pred?
lst).
For example,
> (tally odd? (list 1 2 3 4 5))
3
> (tally even? (list 1 2 3 4 5))
2
; Count dark colors
> (tally (lambda (c) (< (rgb-brightness c) 25)) colors-rainbow)
3
; Count dark, non-dark, and light colors using very concise notation.
> (tally (o (r-s < 25) rgb-brightness) colors-rainbow)
3
> (tally (o (r-s > 25) rgb-brightness) colors-rainbow)
4
> (tally (o (r-s > 75) rgb-brightness) colors-rainbow)
1
Filtering and Selecting
We also use predicates to iterate through lists when we want to
remove all the values in the list that meet some predicate, or
to select all the values in a list for which some predicate holds.
We typically call those procedures (filter
pred? lst)
and (select pred?
lst).
> (filter odd? (list 1 2 3 4 5 6 7))
(2 4 6)
> (filter even? (list 1 2 3 4 5 6 7))
(1 3 5 7)
; Remove dark colors from the rainbow
> (map rgb->color-name (filter (o (r-s < 25) rgb-brightness) colors-rainbow))
("red" "orange" "yellow" "green")
> (select odd? (list 1 2 3 4 5 6 7))
(1 3 5 7)
> (select even? (list 1 2 3 4 5 6 7))
(2 4 6)
; Select the dark colors in the rainbow
> (map rgb->color-name (select (o (r-s < 25) rgb-brightness) colors-rainbow))
("blue" "indigo" "violet")