We saw examples of advanced recursion, and saw how
it differed from embedded and tail recursion.
Tail recursion doesn't have to keep track of the embedded function, so it's more efficient.
Sometimes we had a recursive procedure which called another
recursive procedure which called another, etc.
Sometimes there were multiple recursive calls within a procedure!
Overall, Recursion is easily one of the most powerful
ideas of the course.
It's the only thing CS61A cares about as a prerequisite!
Higher-Order Functions
(chapter 8)
Introduction (and First-class data)
Data is first-class if:
It can be an argument to a procedure
It can be the return value from a procedure
It can be given a name
It can be part of a data aggregate
In Scheme, words, sentences, booleans and procedures (and
some other types you'll see soon) are all first-class
You haven't yet been shown how to aggregate booleans and procedures (which can't be stored in a sentence or word)
-- you'll see that in the post-midterm material
In most other languages, procedures are not first-class (this is a really powerful idea, that functions can be data)
Fish metaphor...
We'll now consider functions that take functions as input!
We'll see some that even return functions.
Using these as tools will allow us to solve hard problems
by simply choosing the combination and composition of the right
tools.
every : Do something to every
word in a sentence
(everyfunction sentence-or-word)
Domain: Every takes two arguments.
The first argument must be a function, and the second is
a word or sentence
The argument function must take one argument, and its domain
must include words. Its range must be words or sentences.
Range: sentences. It returns of results from applying function
to every element of sentence-or-word
This is a mapping pattern
You have just seen a function that takes another function
as input...like a fish that eats other fish!
Examples:
pluralizing, numberizing
keep : Keep only the words or letters you
want
(keeptest sentence-or-word)
This takes a predicate function and a sentence (or word)
as its input
Returns: the elements of sentence-or-word
that satisfy test
If input was sentence, output is sentence
If input was word, output is word.
Unlike every which always output sentences
This is a filtering pattern
Examples: keeping a-words, vowels
accumulate : Combine the
words in some way
(accumulate function sentence-or-word)
This applies a binary (two-argument) function to a sentence-or-word.,
two elements at a time.
If called on one argument, it returns that argument.
Otherwise, the function is applied to the last two elements,
then to the third from last and the result of that, etc.
or, and are special forms, they can't be
used as input!
In 99% of the case, the input function is associative, so this right-associative order of the pairings doesn't matter.