Lab 0.2:
More Practice with Scheme
Scheme is a dialect of Lisp, i.e.
"the greatest single programming language ever designed" -- Alan Kay
Why do we learn it?
"Lisp is worth learning for the profound enlightenment experience you will have when you finally get it;
that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot." -- Eric Raymond
The big idea for this lesson is deceptively simple. It's that we can take the
value returned by one function and use it as an argument to another function.
By “hooking up” two functions in this way, we invent a new, third function.
For example, let's say we have a function that adds the
letter s to the end of a word (in pseudo-code):
add-s(“run”) = “runs”
and another function that puts two words together into a sentence:
sentence(“day”, “tripper”) = “day tripper”
We can combine these to create a new function that represents the third
person singular form of a verb:
third-person(verb) = sentence(“she”, add-s(verb))
That general formula looks like this when applied to a particular verb:
third-person(“sing”) = “she sings”
The way we say it in Scheme is
(define (third-person verb)
(sentence 'she (add-s verb)))
We know that this idea probably doesn't look like much of a big deal to you.
It might seem obvious. Nevertheless, it will turn out that we can express a wide
variety of computational algorithms by linking functions together in this way.
This linking is what we mean by “functional programming.”
Homework
do this in section if possible; finish the rest at home
Exercise 4.
Write a procedure insert-and
that takes a sentence of
items and returns a new sentence with an and
in the right place.
Exercise 5.
Write a procedure query
that turns a statement into a
question by swapping the first two words and adding a question mark to the last
word:
Exercise 6.
Write a procedure european-time
to convert a time
from American AM/PM notation into European 24-hour notation. Also write
american-time
, which does the opposite:
Exercise 7.
Write a procedure describe-time
that takes a number
of seconds as its argument and returns a more useful description of that
amount of time. Assume that there are 365.25 days in a year.
Exercise 8.
The following program doesn't work. Why not? Fix it.
(define (superlative adjective word)
(se (word adjective 'est) word))
If you're stuck, take a look at
Simply Scheme Ch. 7 - Variables