Every data definition in Fixed-Size Data describes data of a fixed size. To us, boolean values, numbers, strings, and images are atomic; computer scientists say they have a size of one unit. With a structure, you compose a fixed number of pieces of data. Even if you use the language of data definitions to create deeply nested structures, you always know the exact number of atomic pieces of data in any specific instance. Many programming problems, however, deal with an undetermined number of pieces of information that must be processed as one piece of data. For example, one program may have to compute the average of a bunch of numbers and another may have to keep track of an arbitrary number of objects in an interactive game. Regardless, it is impossible with your knowledge to formulate a data definition that can represent this kind of information as data.
This part revises the language of data definitions so that it becomes possible to describe data of (finite but) arbitrary size. For a concrete illustration, the first half of this part deals with lists, a form of data that appears in most modern programming languages. In parallel to the extended language of data definitions, this part also revises the design recipe to cope with such data definitions. The latter chapters demonstrate how these data definitions and the revised design recipe work in a variety of contexts.
This chapter introduces self-referential data definitions, that is, definitions that refer to themselves. It is highly unlikely that you have encountered such definitions before. Your English teachers certainly stay away from these, and many mathematics courses are somewhat vague when it comes to such definitions. Programmers cannot afford to be vague; programming languages call for precise definitions.
Lists are one ubiquitous instance of self-referential data definitions. With lists, our programming examples become interesting, which is why this chapter introduces them and shows some ways of manipulating them. It thus motivates the revision of the design recipe in the next chapter, which explains how to systematically create functions that deal with self-referential data definitions.
All of us make lists all the time. Before we go grocery shopping, we write down a list of items we wish to purchase. Some people write down a to-do list every morning. During December, many children prepare Christmas wish lists. To plan a party, we make a list of invitees. Arranging information in the form of lists is a ubiquitous part of our life.
Given that information comes in the shape of lists, we must clearly learn how to represent such lists as BSL data. Indeed, because lists are so important BSL comes with built-in support for creating and manipulating lists, similar to the support for Cartesian points (posn). In contrast to points, the data definition for lists is always left to you. But first things first. We start with the creation of lists.
(cons "Mercury" '())
Because even good artists would have problems with drawing deeply nested structures, computer scientists resort to box-and-arrow diagrams instead. Figure 34 illustrates how to re-arrange the last row of figure 33. Each cons structure becomes a separate box. If the rest field is too complex to be drawn inside of the box, we draw a bullet instead and a line with an arrow to the box that it contains. Depending on how the boxes are arranged you get two kinds of diagrams. The first, displayed in the top row of figure 34, lists the boxes in the order in which they are created. The second, displayed in the bottom row, lists the boxes in the order in which they are consed together. Hence the second diagram immediately tells you what first would produced when applied to the list, no matter how long the list is. For this reason, people tend to prefer the second arrangement.
a list of celestial bodies, say, at least all the planets in our solar system;
a list of items for a meal, for example, steak, French fries, beans, bread, water, brie cheese, and ice cream; and
a list of colors.
; A List-of-names is one of: ; – '() ; – (cons String List-of-names) ; interpretation a List-of-names represents a list of invitees by last name
(cons "Findler" '())
Now that we know why our first self-referential data definition makes sense, let us take another look at the definition itself. Looking back we see that all the original examples in this section fall into one of two categories: start with an '() list or use cons to add something to an existing list. The trick then is to say what kind of “existing lists” you wish to allow, and a self-referential definition ensures that you are not restricted to lists of some fixed length.
9.2 What Is '(), What Is cons
Let us step back for a moment and take a close look at '() and cons. As mentioned, '() is just a constant. When compared to constants such as 5 or "this is a string", it looks more like a function name or a variable; but when compared with #true and #false, it should be easy to see that it really is just BSL’s representation for empty lists.
> (cons 1 2)
cons: second argument must be a list, but received 1 and 2
; A ConsOrEmpty is one of: ; – '() ; – (cons Any ConsOrEmpty) ; interpretation ConsOrEmpty is the class of all BSL lists ; Any ConsOrEmpty -> ConsOrEmpty (define (our-cons a-value a-list) (cond [(empty? a-list) (make-pair a-value a-list)] [(our-cons? a-list) (make-pair a-value a-list)] [else (error "cons: list as second argument expected")]))
If your program can access the structure type definition for pair, it is easy to create pairs that don’t contain '() or another pair in the right field. Whether such bad instances are created intentionally or accidentally, they tend to break functions and programs in strange ways. BSL therefore hides the actual structure type definition for cons to avoid these problems. Local Function Definitions demonstrates one way how your programs can hide such definitions, too, but for now, you don’t need this power.
a special value, mostly to represent the empty list
a predicate to recognize '() and nothing else
a checked constructor to create two-field instances
the selector to extract the last item added
the selector to extract the extended list
a predicate to recognizes instances of cons
Figure 35 summarizes this section. The key insight is that '() is a unique value and that cons is a checked constructor that produces list values. Furthermore, first, rest, and cons? are merely distinct names for the usual predicate and selectors. What this chapter teaches then is not a new way of creating data but a new way of formulating data definitions.
Here we use the word “friend” in the sense of social networks, not the real world.
Sample Problem: You are working on the contact list for some new cell phone. The phone’s owner updates—
adds and deletes names— and consults this list— looks for specific names— on various occasions. For now, you are assigned the task of designing a function that consumes this list of contacts and determines whether it contains the name “Flatt.”
; List-of-names -> Boolean ; determines whether "Flatt" occurs on a-list-of-names (define (contains-flatt? a-list-of-names) #false)
(check-expect (contains-flatt? '()) #false)
(check-expect (contains-flatt? (cons "Findler" '())) #false) (check-expect (contains-flatt? (cons "Flatt" '())) #true)
(check-expect (contains-flatt? (cons "Mur" (cons "Fish" (cons "Find" '())))) #false) (check-expect (contains-flatt? (cons "A" (cons "Flatt" (cons "C" '())))) #true)
Take a breath. Run the program. The header is a “dummy” definition for the function; you have some examples; they have been turned into tests; and best of all, some of them actually succeed. They succeed for the wrong reason but succeed they do. If things make sense now, read on.
Fortunately, we have just such a function: contains-flatt?, which according to its purpose statement determines whether a list contains "Flatt". The purpose statement implies that if l is a list of strings, (contains-flatt? l) tells us whether l contains the string "Flatt". Similarly, (contains-flatt? (rest l)) determines whether the rest of l contains "Flatt". And in the same vein, (contains-flatt? (rest a-list-of-names)) determines whether or not "Flatt" is in (rest a-list-of-names), which is precisely what we need to know now.
; List-of-names -> Boolean ; determines whether "Flatt" occurs on a-list-of-names (check-expect (contains-flatt? (cons "Mur" (cons "Fish" (cons "Find" '())))) #false) (check-expect (contains-flatt? (cons "A" (cons "Flatt" (cons "C" '())))) #true) (define (contains-flatt? a-list-of-names) (cond [(empty? a-list-of-names) #false] [(cons? a-list-of-names) (or (string=? (first a-list-of-names) "Flatt") (contains-flatt? (rest a-list-of-names)))]))
Here then is the complete definition: figure 36. Overall it doesn’t look too different from the definitions in the first chapter of the book. It consists of a signature, a purpose statement, two examples, and a definition. The only way in which this function definition differs from anything you have seen before is the self-reference, that is, the reference to contains-flatt? in the body of the define. Then again, the data definition is self-referential, too, so in some sense this second self-reference shouldn’t be too surprising.
What answer do you expect?
Exercise 134. Here is another way of formulating the second cond clause in contains-flatt?:
Note BSL actually comes with member?, a function that consumes two values and checks whether the first occurs in the second, which must be a list:Don’t use member? to define the contains? function.
== (cond [#false #false] [(cons? (cons "Flatt" (cons "C" '()))) (or (string=? (cons "Flatt" (cons "C" '())) "Flatt") (contains-flatt? (rest (cons "Flatt" (cons "C" '())))))]) == (cond [(cons? (cons "Flatt" (cons "C" '()))) (or (string=? (cons "Flatt" (cons "C" '())) "Flatt") (contains-flatt? (rest (cons "Flatt" (cons "C" '())))))]) == (cond [#true (or (string=? (first (cons "Flatt" (cons "C" '()))) "Flatt") (contains-flatt? (rest (cons "Flatt" (cons "C" '())))))]) == (or (string=? (first (cons "Flatt" (cons "C" '()))) "Flatt") (contains-flatt? (rest (cons "Flatt" (cons "C" '())))))
Also use the stepper to determine the value ofWhat happens when "Flatt" is replaced with "B"?
(our-first (our-cons "a" '())) == "a" (our-rest (our-cons "a" '())) == "a"See What Is '(), What Is cons for the definitions of these functions.
If a problem statement discusses compound information of arbitrary size, you need a self-referential data definition. At this point, you have seen only one such class, List-of-names. The left side of figure 37 shows how to define List-of-strings in the same way. It is also straightforward to imagine lists of Numbers, lists of Booleans, lists of Images, and so on.
Numbers also seem to be arbitrarily large. For inexact numbers, this is an illusion. For precise integers, this is indeed the case. Dealing with integers is therefore a part of this chapter.
For a self-referential data definition to be valid, it must satisfy two conditions. First, it must contain at least two clauses. Second, at least one of the clauses must not refer back to the class of data that is being defined. It is good practice to identify the self-references explicitly with arrows from the references in the data definition back to the term being defined; see figure 37 for an example of such an annotation.You must check the validity of self-referential data definitions with the creation of examples. Start with the clause that does refer to the data definition; then use the other one with the first example. For the data definition in figure 37, you thus get lists like the following three:
If it is impossible to generate examples from the data definition, it is invalid. If you can generate examples but you can’t see how to generate larger and larger examples, the definition may not live up to its interpretation.
Nothing changes about the header material: the signature, the purpose statement, and the dummy definition. When you do formulate the purpose statement, focus on what the function computes not how it goes about it, especially not how it goes through instances of the given data.Here is an example to make this design recipe concrete:The purpose statement clearly states that the function just counts the strings on the given input; there is no need to think ahead about how you might formulate this idea as a BSL function.
When it comes to functional examples, be sure to work through inputs that use the self-referential clause of the data definition several times. It is the best way to formulate tests that cover the entire function definition later.For our running example, the purpose statement almost generates functional examples by itself from the data examples:The first row is about the empty list, and we know that empty list contains nothing. The second row is a list of one string, so 1 is the desired answer. The last row is about a list of two strings.
At the core, a self-referential data definition looks like a data definition for mixed data. The development of the template can therefore proceed according to the recipe in Itemizations and Structures. Specifically, we formulate a cond expression with as many cond clauses as there are clauses in the data definition, match each recognizing condition to the corresponding clause in the data definition, and write down appropriate selector expressions in all cond lines that process compound values.
Does the data definition distinguish among different subclasses of data?
Your template needs as many cond clauses as subclasses that the data definition distinguishes.
How do the subclasses differ from each other?
Use the differences to formulate a condition per clause.
Do any of the clauses deal with structured values?
If so, add appropriate selector expressions to the clause.
Does the data definition use self-references?
Formulate “natural recursions” for the template to represent the self-references of the data definition.
If the data definition refers to some other data definition, where is this cross-reference to another data definition?
Specialize the template for the other data definition. Refer to this template. See Designing with Itemizations, Again, steps 4 and 5 of the design recipe.
Figure 38 expresses this idea as a question-and-answer game. In the left column it states questions about the data definition for the argument, and in the right column it explains what the answer means for the construction of the template.If you ignore the last row and apply the first three questions to any function that consumes a List-of-strings, you arrive at this shape:
Recall, though, that the purpose of a template is to express the data definition as a function layout. That is, a template expresses as code what the data definition for the input expresses as a mix of English and BSL. Hence all important pieces of the data definition must find a counterpart in the template, and this guideline should also hold when a data definition is self-referential—
contains an arrow from inside the definition to the term being defined. In particular, when a data definition is self-referential in the ith clause and the kth field of the structure mentioned there, the template should be self-referential in the ith cond clause and the selector expression for the kth field. For each such selector expression, add an arrow back to the function parameter. At the end, your template must have as many arrows as we have in the data definition.
Figure 37 illustrates this idea with the template for functions that consume List-of-strings shown side by side with the data definition. Both contain one self-referential arrow that originates in the second clause—
the rest field and selector, respectively— and points back to the top of the respective definitions.Since BSL and most programming languages are text-oriented, you must use an alternative to the arrow, namely, a self-applications of the function to the appropriate selector expression:We refer to a self-use of a function as recursion and in the first four parts of the book as natural recursion.
For the function body we start with thoseFor the curious among our readers, the design recipe for arbitrarily large data corresponds to so-called “proofs by induction” in mathematics and the “leap of faith” represents the assumption of the induction hypothesis for the inductive step of such a proof. Courses on logic prove the validity of this proof technique with a so-called Induction Theorem. cond lines that do not contain natural recursions. They are called base cases.The corresponding answers are typically easy to formulate or are already given by the examples.
Then we deal with the self-referential cases. We start by reminding ourselves what each of the expressions in the template line computes. For the natural recursion we assume that the function already works as specified in our purpose statement. This last step is a leap of faith, but as you will see, it always works.
The rest is then a matter of combining the various values.
What are the answers for the non-recursive cond clauses?
The examples should tell you which values you need here. If not, formulate appropriate examples and tests.
What do the selector expressions in the recursive clauses compute?
The data definitions tell you what kind of data these expressions extract and the interpretations of the data definitions tell you what this data represents.
What do the natural recursions compute?
Use the purpose statement of the function to determine what the value of the recursion means not how it computes this answer. If the purpose statement doesn’t tell you the answer, improve the purpose statement.
How can the function combine these values to get the desired answer?
Find a function in BSL that combines the values. Or, if that doesn’t work, make a wish for a helper function. For many functions, this last step is straightforward. The purpose, the examples, and the template together tell you which function or expression “combines” the available values into the proper result. We refer to this function or expression as combinator, slightly abusing existing terminology.
So, if you are stuck here, ...
... arrange the examples from the third step in a table. Place the given input in the first column and the desired output in the last column. In the intermediate columns enter the values of the selector expressions and the natural recursion(s). Add examples until you see a pattern emerge that suggests a combinator.
If the template refers to some other template, what does the auxiliary function compute?
Consult the other function’s purpose statement and examples to determine what it computes and assume you may use the result even if you haven’t finished the design of this helper function.Figure 39 formulates questions and answers for this step. Let’s use this game to complete the definition of how-many. Renaming the fun-for-los template to how-many gives us this much:As the functional examples already suggest, the answer for the base case is 0. The two expressions in the second clause compute the first item and the number of strings in (rest alos). To compute how many strings there are on all of alos, we just need to add 1 to the value of the latter expression:
Dr. Felix Klock suggested this table-based approach to guessing the combinator.Finding the correct way to combine the values into the desired answer isn’t always as easy. Novice programmers often get stuck with this step. As the question-and-answer game suggests, it is a good idea to arrange the functional examples into a table that also spells out the values of the expressions in the template. Figure 40 shows what this table looks like for our how-many example. The leftmost column lists the sample inputs, while the rightmost column contains the desired answers for these inputs. The three columns in between show the values of the template expressions: (first alos), (rest alos), and (how-many (rest alos)), which is the natural recursion. If you stare at this table long enough, you recognize that the result column is always one more than the values in the natural recursion column. You may thus guess thatis the expression that computes the desired result. Since DrRacket is fast at checking these kinds of guesses, plug it in and click RUN. If the examples-turned-into-tests pass, think through the expression to convince yourself it works for all lists; otherwise add more example rows to the table until you have a different idea.
The table also points out that not all selector expressions in the template are necessarily relevant for the function definition. Here (first alos) is not needed to compute the final answer—
which is quite a contrast to contains-flatt?, which uses both expressions from the template.
As you work your way through the rest of this book, keep in mind that, in many cases, the combination step can be expressed with BSL’s primitives, say, +, and, or cons. In some cases, though, you may have to make a wish, that is, design an auxiliary function. Finally, in yet other cases, you may need nested conditions.
Finally, make sure to turn all examples into tests, that these tests pass, and that running them covers all the pieces of the function.Here are our examples for how-many turned into tests:
(check-expect (how-many '()) 0) (check-expect (how-many (cons "a" '())) 1) (check-expect (how-many (cons "b" (cons "a" '()))) 2)Remember it is best to formulate examples directly as tests and BSL allows this. Doing so also helps if you need to resort to the table-based guessing approach of the preceding step.
Figure 41 summarizes the design recipe of this section in a tabular format. The first column names the steps of the design recipe, the second the expected results of each step. In the third column, we describe the activities that get you there. The figure is tailored to the kind of self-referential list definitions we use in this chapter. As always, practice helps you master the process, so we strongly recommend that you tackle the following exercises, which ask you to apply the recipe to several kinds of examples.
You may want to copy figure 41 onto one side of an index card and write down your favorite versions of the questions and answers in figure 38 and figure 39 onto the back of it. Then carry it with you for future reference. Sooner or later, the design steps become second nature and you won’t think about them anymore. Until then, refer to your index card whenever you are stuck with the design of a function.
identify the information that must be represented; develop a data representation; know how to create data for a specific item of information and how to interpret a piece of data as information; identify self-references in the data definition
signature; purpose statement; dummy definition
write down a signature, using the names from the data definitions; formulate a concise purpose statement; create a dummy function that produces a constant value from the specified range
examples and tests
work through several examples, at least one per clause in the (self-referential) data definition; turn them into check-expect tests
translate the data definition into a template: one cond clauses per clause; one condition per clause to distinguish the cases; selector expressions per clause if the condition identifies a structure; one natural recursion per self-reference in the data definition
find a function that combines the values of the expressions in the cond clauses into the expected answer
run the tests and validate that they all pass
; A List-of-amounts is one of: ; – '() ; – (cons PositiveNumber List-of-amounts) ; interpretation a List-of-amounts represents some amounts of moneyCreate some examples to make sure you understand the data definition. Also add an arrow for the self-reference.
Some elements of this class of data are appropriate inputs for sum from exercise 139 and some aren’t.
Design the function pos?, which consumes a List-of-numbers and determines whether all numbers are positive numbers. In other words, if (pos? l) yields #true, then l is an element of List-of-amounts. Use DrRacket’s stepper to understand how pos? works for (cons 5 '()) and (cons -1 '()).
What does sum compute for an element of List-of-numbers?
all-true, which consumes a list of Boolean values and determines whether all of them are #true. In other words, if there is any #false on the list, the function produces #false; otherwise it produces #true.
one-true, which consumes a list of Boolean values and determines whether at least one item on the list is #true.Follow the design recipe: start with a data definition for lists of Boolean values and don’t forget to make up examples. You may also wish to employ the table-based guessing approach; it tends to help understand the answer needed for the base case.
Exercise 142. If you are asked to design the function cat, which consumes a list of strings and appends them all into one long string, you are guaranteed to end up with this partial definition:
; List-of-string -> String ; concatenate all strings in l into one long string (check-expect (cat '()) "") (check-expect (cat (cons "a" (cons "b" '()))) "ab") (check-expect (cat (cons "ab" (cons "cd" (cons "ef" '())))) "abcded") (define (cat l) (cond [(empty? l) ""] [else (... (first l) ... (cat (rest l)) ...)]))Fill in the table below:Guess a function that can create the desired result from the values computed by the subexpressions.
Use DrRacket’s stepper to evaluate (cat (cons "a" '())).
Exercise 143. Design ill-sized?. The function consumes a list of images loi and a positive number n. It produces the first image on loi that is not an n by n square; if it cannot find such an image, it produces #false.Hint Use
; ImageOrFalse is one of: ; – Image ; – #falsefor the result part of the signature.
Now you know enough to use cons and to create data definitions for lists. If you solved (some of) the exercises at the end of the preceding section, you can deal with lists of various flavors of numbers, lists of Boolean values, lists of images, and so on. In this section we continue to explore what lists are and how to process them.
; A List-of-temperatures is one of: ; – '() ; – (cons CTemperature List-of-temperatures) ; A CTemperature is a Number greater or equal to -273.
The problem is that it was too difficult to turn this template into a working function definition. The first cond clause needs a number that represents the average of an empty collection of temperatures, but there is no such number. Even if we ignore this problem for a moment, the second clause demands a function that combines a temperature and an average for many other temperatures into another average. Although it is isn’t impossible to compute this average, it is not what you learned to do and it isn’t natural.
; List-of-temperatures -> Number ; computes the average temperature (define (average alot) (/ (sum alot) (how-many alot))) ; List-of-temperatures -> Number ; adds up the temperatures on the given list (define (sum alot) 0) ; List-of-temperatures -> Number ; counts the temperatures on the given list (define (how-many alot) 0)
When you read this definition of average now, it is obviously correct simply because it directly corresponds to what everyone learns about averaging in school. Still, programs run not just for us but for others. In particular, others should be able to read the signature and use the function and expect an informative answer. But, our definition of average does not work for empty lists of temperatures.
Exercise 144. Determine how average behaves in DrRacket when applied to the empty list of temperatures. Then design checked-average, a function that produces an informative error message when it is applied to '().
From a theoretical perspective, exercise 144 shows that average is a partial function because it raises an error for '(). The alternative development explains that, in this case, we can narrow down the domain and create a total function.
; A NEList-of-temperatures is one of: ; – (cons CTemperature '()) ; – (cons CTemperature NEList-of-temperatures) ; interpretation non-empty lists of measured temperatures
(cons ccc '())
; NEList-of-temperatures -> Number ; computes the average temperature (check-expect (average (cons 1 (cons 2 (cons 3 '())))) 2) (define (average anelot) (/ (sum anelot) (how-many anelot)))
Exercise 145. Would sum and how-many work for NEList-of-temperatures even if they were designed for inputs from List-of-temperatures? If you think they don’t work, provide counter-examples. If you think they would, explain why.
; NEList-of-temperatures -> Number ; computes the sum of the given temperatures (check-expect (sum (cons 1 (cons 2 (cons 3 '())))) 6) (define (sum anelot) 0)
Exercise 146. Design sorted>?. The function consumes a NEList-of-temperatures. It produces #true if the temperatures are sorted in descending order, that is, if the second is smaller than the first, the third smaller than the second, and so on. Otherwise it produces #false.
Hint Consider using the table-based guessing approach; it tends to help understand the answer needed for the base case.Hint This problem is another one where the table-based method for guessing the combinator. Here is a partial table for a number of examples:Fill in the rest of the table. Then try to create an expression that computes the result from the pieces.
Exercise 147. Design how-many for NEList-of-temperatures. Doing so completes average, so ensure that average passes all of its tests, too.
Exercise 148. Develop a data definition for NEList-of-Booleans, a representation of non-empty lists of Boolean values. Then re-design the functions all-true and one-true from exercise 141.
Exercise 149. Compare the function definitions from this section (sum, how-many, all-true, one-true) with the corresponding function definitions from the preceding sections. Is it better to work with data definitions that accommodate empty lists as opposed to definitions for non-empty lists? Why? Why not?
Let us take a close look at the data definition of natural numbers. The first clause says that 0 is a natural number; it is of course used to say that there is no object to be counted. The second clause tells you that if n is a natural number, then n+1 is one too, because add1 is a function that adds 1 to whatever number it is given. We could write this second clause as (+ n 1) but the use of add1 is supposed to signal that this addition is special.
What is special about this use of add1 is that it acts more like a constructor from some structure type definition than a regular numeric function. For that reason, BSL also comes with the function sub1, which is the “selector” corresponding to add1. Given any natural number m not equal to 0, you can use sub1 to find out the number that went into the construction of m. Put differently, add1 is like cons and sub1 is like first and rest.
At this point you may wonder what the predicates are that distinguish 0 from those natural numbers that are not 0. There are two, just as for lists: zero?, which determines whether some given number is 0, and positive?, which determines whether some number is larger than 0.
; N String -> List-of-strings ; creates a list of n strings s (check-expect (copier 2 "hello") (cons "hello" (cons "hello" '()))) (check-expect (copier 0 "hello") '()) (define (copier n s) '())
; N String -> List-of-strings ; creates a list of n strings s (check-expect (copier 2 "hello") (cons "hello" (cons "hello" '()))) (check-expect (copier 0 "hello") '()) (define (copier n s) (cond [(zero? n) '()] [(positive? n) (cons s (copier (sub1 n) s))]))
At this point, you should run the tests to ensure that this function works at least for the two worked examples. In addition, you may wish to use the function on some additional inputs.
Exercise 150. Does copier function properly when you apply it to a natural number and a Boolean or an image? Or do you have to design another function? Read Similarities Everywhere for an answer.An alternative definition of copier might use else for the second condition:How do copier and copier.v2 behave when you apply them to 0.1 and "xyz"? Explain. Use DrRacket’s stepper to confirm your explanation.
Exercise 151. Design the function add-to-pi. It consumes a natural number n and adds it to pi without using + from BSL. Here is a start:
Exercise 152. Design the function multiply. It consumes a natural number n and multiplies it with some arbitrary number x without using *.
Use DrRacket’s stepper to evaluate (multiply 3 x) for any x you like. How does multiply relate to what you know from grade school.
The function col consumes a natural number n and an image img. It produces a column—
a vertical arrangement— of n copies of img.
The function row consumes a natural number n and an image img. It produces a row—
a horizontal arrangement— of n copies of img.
Exercise 154. The goal of this exercise is to visualizes the result of a 1968-style European student riot. Here is the rough idea. A small group of students meets to make paint-filled balloons, enters some lecture hall and randomly throws the balloons at the attendees. Your world program displays how the balloons color the seats in the lecture hall.
Design add-balloons. The function consumes a list of Posn whose coordinates fit into the dimensions of the lecture hall. It produces an image of the lecture hall with red dots added as specified by the Posns.Here are outputs of our solution when given some list of Posns:
The leftmost is the clean lecture hall, the second one is after two balloons have hit, and the last one is a highly unlikely distribution of 10 hits. Where is the 10th?
The problem may strike you as somewhat abstract or even absurd; after all it isn’t clear why you would want to represent Russian dolls or what you would do with such a representation. Suspend your disbelief and read along; it is a worthwhile exercise.
Now consider the problem of representing such Russian dolls with BSL data. With a little bit of imagination, it is easy to see that an artist can create a nest of Russian dolls that consists of an arbitrary number of dolls. After all, it is always possible to wrap another layer around some given Russian doll. Then again, you also know that deep inside there is a solid doll without anything inside.
For each layer of a Russian doll, we could care about many different things: its size, though it is related to the nesting level; its color; the image that is painted on the surface; and so on. Here we just pick one, namely the color of the doll, which we represent with a string. Given that, we know that each layer of the Russian doll has two properties: its color and the doll that is inside. To represent pieces of information with two properties, we always define a structure type:
(make-layer "green" "red")
(make-layer "yellow" (make-layer "green" "red"))
(make-layer "pink" (make-layer "black" "white"))
(layer-color an-rd) extracts the string that describes the color of the current layer;
(layer-doll an-rd) extracts the doll contained within the current layer; and
according to the purpose statement, (depth (layer-doll an-rd)) determines how many dolls (layer-doll an-rd) consists of.
(check-expect (depth (make-layer "yellow" (make-layer "green" "red"))) 3) (check-expect (depth "red") 1)
Exercise 155. Design the function colors. It consumes a Russian doll and produces a string of all colors, separate by a comma and a space. Thus our example should produce
"yellow, green, red"
Exercise 156. Design the function inner, which consumes an RD and produces the (color of the) innermost doll. Use DrRacket’s stepper to evaluate (inner rd) for you favorite rd.
Sample Problem: Design a world program that simulates firing shots. Every time the “player” hits the space bar, the program adds a shot to the bottom of the canvas. These shots rise vertically at the rate of one pixel per tick.
; A List-of-shots is one of: ; – '() ; – (cons Shot List-of-shots) ; interpretation the collection of shots fired and moving straight up
; A ShotWorld is List-of-numbers. ; interpretation each number represents the y-coordinate of a shot
; physical constants (define HEIGHT 80) (define WIDTH 100) (define XSHOTS (/ WIDTH 2)) ; graphical constants (define BACKGROUND (empty-scene WIDTH HEIGHT)) (define SHOT (triangle 3 "solid" "red")) ; A ShotWorld is List-of-numbers. ; interpretation the collection of shots fired and moving straight up ; ShotWorld -> ShotWorld (define (main w0) (big-bang w0 [on-tick tock] [on-key keyh] [to-draw to-image])) ; ShotWorld -> ShotWorld ; moves each shot up by one pixel (define (tock w) (cond [(empty? w) '()] [else (cons (sub1 (first w)) (tock (rest w)))])) ; ShotWorld KeyEvent -> ShotWorld ; adds a shot to the world if the space bar was hit (define (keyh w ke) (cond [(key=? ke " ") (cons HEIGHT w)] [else w])) ; ShotWorld -> Image ; adds each y on w at (MID,y) to the background image (define (to-image w) (cond [(empty? w) BACKGROUND] [else (place-image SHOT XSHOTS (first w) (to-image (rest w)))]))
Figure 43 displays the complete function definition for to-image and indeed the rest of the program, too. The design of tock is just like the design of to-image and you should work through it for yourself. The signature of the keyh handler, though, poses one interesting question. It specifies that the handler consumes two inputs with non-trivial data definitions. On one hand, the ShotWorld is self-referential data definition. On the other hand, the definition for KeyEvents is a large enumeration. For now, we have you “guess” which of the two arguments should drive the development of the template; later we will study such cases in depth.
Exercise 157. Equip the program in figure 43 with tests and make sure it passes those. Explain what main does. Then run the program via main.
Exercise 158. Experiment whether the arbitrary decisions concerning constants are truly easy to change. For example, determine whether changing a single constant definition achieves the desired outcome:
change the height of the canvas to 220 pixels;
change the width of the canvas to 30 pixels;
change the x location of the line of shots to “somewhere to the left of the middle;”
change the background to a green rectangle; and
change the rendering of shots to a red elongated rectangle.Also check whether it is possible to double the size of the shot without changing anything else, change its color to black, or change its form to "outline".
Exercise 159. If you run main, press the space bar (fire a shot), and wait for a good amount of time, the shot disappears from the canvas. When you shut down the world canvas, however, the result is a world that still contains this invisible shot.
Design an alternative tock function, which not just moves shots one pixel per clock tick but also eliminates those whose coordinates places them above the canvas. Hint You may wish to consider the design of an auxiliary function for the recursive cond clause.
Exercise 160. Turn the exercise of exercise 154 into a world program. Its main function, dubbed riot, consumes how many balloons the students want to throw; its visualization shows one balloon dropping after another at a rate of one per second. The function produces the list of Posns where the balloons hit.Hints (1) Here is one possible data representation:
(define-struct pair [balloon# lob]) ; A Pair is a structure (make-pair N List-of-posns) ; A List-of-posns is one of: ; – '() ; – (cons Posn List-of-posns) ; interpretation (make-pair n lob) means n ; balloons must yet be thrown and the thrown balloons landed at lob
(2) A big-bang expression is really just an expression. It is legitimate to nest it within an expression.
(3) Recall that random creates random numbers.
Lists are a versatile form of data that come with almost all languages now. Programmers have used them to build large applications, artificial intelligences, distributed systems, and more. This chapter illustrates some basic ideas from this world, including functions that create lists, data representations that call for structures inside of lists, and representing text files as lists.
Call this new function wage*. Its task is to process all employee work hours and to determine the wages due to each of them. For simplicity, let us assume that the input is a list of numbers, each representing the number of hours that one employee worked, and that the expected result is a list of the weekly wages earned, also represented with a list of numbers.
; List-of-numbers -> List-of-numbers ; computes the weekly wages for all given weekly hours (define (wage* alon) '())
It is now time for the most creative design step. Following the design recipe, we consider each cond-line of the template in isolation. For the non-recursive case, (empty? alon) is true, meaning the input is '(). The examples from above specify the desired answer, '(), and so we are done.
(first alon) yields the first number on alon, which is the first number of hours worked;
(rest alon) is the rest of the given list; and
(wage* (rest alon)) says that the rest is processed by the very function we are defining. As always we use its signature and its purpose statement to figure out the result of this expression. The signature tells us that it is a list of numbers, and the purpose statement explains that this list represents the list of wages for its input, which is the rest of the list of hours.
Exercise 161. Translate the examples into tests and make sure they all succeed. Then change the function in figure 44 so that everyone gets $14 per hour. Now revise the entire program so that changing the wage for everyone is a single change to the entire program and not several.
Exercise 162. No employee could possibly work more than 100 hours per week. To protect the company against fraud, the function should check that no item of the input list of wage* exceeds 100. If one of them does, the function should immediately signal an error. How do we have to change the function in figure 44 if we want to perform this basic reality check?
Show the products of the various steps in the design recipe. If you are stuck, show someone how far you got according to the design recipe. The recipe isn’t just a design tool for you to use; it is also a diagnosis system so that others can help you help yourself.
Generalize convert-euro to the function convert-euro*, which consumes an exchange rate and a list of US$ amounts and converts the latter into a list of € amounts.
Generalize subst-robot to the function substitute. The new function consumes two strings, called new and old, and a list of strings. It produces a new list of strings by substituting all occurrences of old with new.
Representing a work week as a number is a bad choice because the printing of a paycheck requires more information than hours worked per week. Also, not all employees earn the same amount per hour. Fortunately a list may contain items other than atomic values; indeed, lists may contain whatever values we want, especially structures.
(define-struct work [employee rate hours]) ; Work is a structure: (make-work String Number Number). ; interpretation (make-work n r h) combines the name (n) ; with the pay rate (r) and the number of hours (h) worked.
; Low (list of works) is one of: ; – '() ; – (cons Work Low) ; interpretation an instance of Low represents the hours worked ; of a number of employees
Stop! Also use the data definition to generate two more examples.
; Low -> List-of-numbers ; computes the weekly wages for all given weekly work records (define (wage*.v2 an-low) '())
The third step of the design recipe is to work through an example. Let us start with the second list above. It contains one work record, namely, (make-work "Robby" 11.95 39). Its interpretation is that "Robby" worked for 39 hours and that he is paid at the rate of $11.95 per hour. Hence his wage for the week is $466.05, i.e., (* 11.95 39). The desired result for wage*.v2 is therefore (cons 466.05 '()). Naturally, if the input list contained two work records, we would perform this kind of computation twice, and the result would be a list of two numbers. Before you read on, determine the expected result for the third data example above.
(first an-low) extracts the first work structure from the list;
(for-work ...) says that you wish to design a function that processes work structures;
(rest an-low) extracts the rest of the given list; and
according to the purpose statement, (wage*.v2 (rest an-low)) determines the list of wages for all the work records other than the first one.
; Low -> List-of-numbers ; computes the weekly wages for all given weekly work records (check-expect (wage*.v2 (cons (make-work "Robby" 11.95 39) '())) (cons (* 11.95 39) '())) (define (wage*.v2 an-low) (cond [(empty? an-low) '()] [(cons? an-low) (cons (wage.v2 (first an-low)) (wage*.v2 (rest an-low)))])) ; Work -> Number ; computes the wage for the given work record w (define (wage.v2 w) (* (work-rate w) (work-hours w)))
Develop a data representation for pay checks. Assume that a pay check contains two pieces of information: the name of the employee and an amount. Then design the function wage*.v3. It consumes a list of work records and computes a list of (representations of) pay checks from it, one per work record.
In reality, a pay check also contains an employee number. Develop a data representation for employee information and change the data definition for work records so that it uses employee information and not just a string for the employee’s name. Also change your data representation of pay checks so that it contains an employee’s name and number, too. Finally, design wage*.v4, a function that maps lists of revised work records to lists of revised pay checks.
Note This exercise demonstrates the iterative refinement of a task. Instead of using data representations that include all relevant information, we started from simplistic representation of pay checks and gradually made the representation realistic. For this simple program, refinement is overkill; later we will encounter situations where iterative refinement is not just an option but a necessity.
Exercise 168. Design the function translate. It consumes and produces lists of Posns. For each (make-posn x y) in the former, the latter contains (make-posn x (+ y 1)).—
We borrow the word “translate” from geometry, where the movement of a point by a constant distance along a straight line is called a translation.
Exercise 169. Design the function legal. Like translate from exercise 168 the function consumes and produces a list of Posns. The result contains all those Posns whose x-coordinates are between 0 and 100 and whose y-coordinates are between 0 and 200.
(define-struct phone [area switch four]) ; A Phone is a structure: ; (make-phone Three Three Four) ; A Three is between 100 and 999. ; A Four is between 1000 and 9999.Design the function replace. It consumes a list of Phones and produces one. It replaces all occurrence of area code 713 with 281.
Functions And Programs introduces read-file, a function for readingUse (require 2htdp/batch-io). an entire text file as a string. In other words, the creator of read-file chose to represent text files as strings, and the function creates the data representation for specific files (specified by a name). Text files aren’t plain long texts or strings, however. They are organized into lines and words, rows and cells, and many other ways. In short, representing the content of a file as a plain string might work on rare occasions but is usually a bad choice.
Put up in a place
where it's easy to see
the cryptic admonishment
When you feel how depressingly
slowly you climb,
it's well to remember that
Things Take Time.
"TTT\n \nPut up in a place\nwhere ..."
- One way to represent this file is as a list of lines, where each line is represented as one string:Here the second item of the list is the empty string because the file contains an empty line.
- Another way is to use a list of all possible words, again each word represented to a string:Note how the empty second line disappears with this representation. After all, there are no words on the empty line.
- And a third representation mixes the first two with a list of list of words:The advantage of this representation over the second one is that it preserves the organization of the file, including the emptiness of the second line. Of course, the price is that all of a sudden lists contain lists.
Before we get started, take a look at figure 46. It introduces a
number of useful file reading functions that come with BSL. They are not
comprehensive and there are many other ways of dealing with text from
files, and you will need to know a lot more to deal with all possible text
files. For our purposes here—
; String -> String ; produces the content of file f as a string (define (read-file f) ...) ; String -> List-of-string ; produces the content of file f as a list of strings, ; one per line (define (read-lines f) ...) ; String -> List-of-string ; produces the content of file f as a list of strings, ; one per word (define (read-words f) ...) ; String -> List-of-list-of-string ; produces the content of file f as a list of list of ; strings, one list per line and one string per word (define (read-words/line f) ...) ; All functions that read a file consume the name of a file ; as a String argument. They assume the specified file ; exists in the same folder as the program; if not they ; signal an error.
One problem with figure 46 is that they use the names of two data definitions that do not exist yet, including one involving list-containing lists. As always, we start with a data definition, but this time, we leave this task to you. Hence, before you read on, solve the following exercises. The solutions are needed to make complete sense out of the figure, and without working through the solutions, you cannot really understand the rest of this section.
Exercise 171. You know what the data definition for List-of-strings looks like. Spell it out. Make sure that you can represent Piet Hein’s poem as an instance of the definition where each line is a represented as a string and another one where each word is a string. Use read-lines and read-words to confirm your representation choices.
Next develop the data definition for List-of-list-of-strings. Again, represent Piet Hein’s poem as an instance of the definition where each line is a represented as a list of strings, one per word, and the entire poem is a list of such line representations. You may use read-words/line to confirm your choice.
As you probably know, operating systems come with programs that measure various statistics of files. Some count the number of lines, others count the number of words in a file. A third may determine how many words appear per line. Let us start with the latter to illustrate how the design recipe helps with the design of complex functions.
; LLS -> List-of-numbers ; determines the number of words on each line (define (words-on-line lls) '())
Once you have data examples, it is easy to formulate functional examples; just imagine applying the function to each of the data example. When apply words-on-line to lls0, you should get the empty list back, because there are no lines. When you apply words-on-line to lls1, you should get a list of two numbers back, because there are two lines. The two numbers are 2 and 0, respectively, given that the two lines in lls1 contain two and no words each.
(first lls) extracts the first line from the non-empty list of (represented) lines;
(line-processor (first lls)) suggests that we may wish to design an auxiliary function to process this line;
(rest lls) is the rest of the list of line;
(words-on-line (rest lls)) computes a list of words per line for the rest of the list. How do we know this? We promised just that with the signature and the purpose statement for words-on-line.
(define (words# los) (how-many los))
; A LLS is one of: ; – '() ; – (cons Los LLS) ; interpretation a list of lines, each line is a list of strings (define line0 (cons "hello" (cons "world" '()))) (define line1 '()) (define lls0 '()) (define lls1 (cons line0 (cons line1 '()))) ; LLS -> List-of-numbers ; determines the number of words on each line (check-expect (words-on-line lls0) '()) (check-expect (words-on-line lls1) (cons 2 (cons 0 '()))) (define (words-on-line lls) (cond [(empty? lls) '()] [else (cons (length (first lls)) (words-on-line (rest lls)))]))
You may wish to look over the rest of functions that come with BSL. Some may look obscure now, but they may just be useful in one of the upcoming problems. Then again, using such functions saves only your time. You just may wish to design them from scratch to practice your design skills or to fill time.
Figure 47 summarizes the full design for our sample problem. The figure includes two test cases. Also, instead of using the separate function words#, the definition of words-on-line simply calls the length function that comes with BSL. Experiment with the definition in DrRacket and make sure that the two test cases cover the entire function definition.
; String -> List-of-numbers ; counts the number of words on each line in the given file (define (file-statistic file-name) (words-on-line (read-words/line file-name)))
This idea of composing a built-in function with a newly designed function is common. Naturally, people don’t design functions randomly and expect to find something in the chosen programming language to complement their design. Instead, program designers plan ahead and design the function to the output that available functions deliver. More generally still and as mentioned above, it is common to think about a solution as a composition of two computations and to develop an appropriate data collection with which to communicate the result of one computation to the second one, where each computation is each implemented with a function.
Challenge: Remove all extraneous white spaces in your version of the Piet Hein poem. When you are finished with the design of the program, use it like this:The two files "ttt.dat" and "ttt.txt" should be identical.
Exercise 173. Design a program that removes all articles from a text file. The program consumes the name n of a file, reads the file, removes the articles, and writes the result out to a file whose name is the result of concatenating "no-articles-" with n. For this exercise, an article is one of the following three words: "a", "an", and "the".
Use read-words/line so that the transformation retains the organization of the original text into lines and words. When the program is designed, run it on the Piet Hein poem.
Exercise 174. Design a program that encodes text files numerically. Each letter in a word should be encoded as a numeric three-letter string with a value between 0 and 256. Here is our encoding function for letters:
; 1String -> String ; converts the given 1string into a three-letter numeric string ; 1String -> String ; auxiliary for stating tests (define (code1 c) (number->string (string->int c))) (check-expect (encode-letter "\t") (string-append "00" (code1 "\t"))) (check-expect (encode-letter "a") (string-append "0" (code1 "a"))) (check-expect (encode-letter "z") (code1 "z")) (define (encode-letter s) (cond [(< (string->int s) 10) (string-append "00" (code1 s))] [(< (string->int s) 100) (string-append "0" (code1 s))] [else (code1 s)]))Before you start, explain this function. Also recall how a string can be converted into a list of 1Strings.
Again, use read-words/line to preserve the organization of the file into lines and words.
Exercise 175. Design a BSL program that simulates the Unix command wc. The purpose of the command is to count the number of 1Strings, words, and lines in a given file. That is, the command consumes the name of a file and produces a value that consists of three numbers.
Exercise 176. Mathematics teachers may have introduced you to matrix calculations by now. Numeric programs deal with those, too. In principle, matrix just means rectangle of numbers. Here is one possible data representation for matrices:Note the constraints on matrices. Study the data definition and translate the two-by-two matrix consisting of the numbers 11, 12, 21, 22 into this data representation. Stop, don’t read on until you have figured out the data examples.Here is the solution for the five-second puzzle:If you didn’t create it yourself, study it now.The following function implements the important mathematical operation of transposing the entries in a matrix. To transpose means to mirror the entries along the diagonal, that is, the line from the top-left to the bottom-right. Again, stop! Transpose mat1 by hand, then read on:
; Matrix -> Matrix ; transpose the items on the given matrix along the diagonal (define wor1 (cons 11 (cons 21 '()))) (define wor2 (cons 12 (cons 22 '()))) (define tam1 (cons wor1 (cons wor2 '()))) (check-expect (transpose mat1) tam1) (define (transpose lln) (cond [(empty? (first lln)) '()] [else (cons (first* lln) (transpose (rest* lln)))]))The definition assumes two auxiliary functions:
first*, which consumes a matrix and produces the first column as a list of numbers;
rest*, which consumes a matrix and removes the first column. The result is a matrix.
Even though you lack definitions for these functions, you should be able to understand how transpose works. You should also understand that you cannot design this function with the design recipes you have seen so far. Explain why.
Design the two “wish list” functions. Then complete the design of the transpose with some test cases.
A Graphical Editor is about the design of an interactive graphical one-line editor. It suggests two different ways to represent the state of the editor and urges you to explore both: a structure that contains pair of strings or a structure that combines a string with an index to a current position (see exercise 87).
- (make-editor pre post) could mean the letters in pre precede the cursor and those in post succeed it and that the combined text is
- (make-editor pre post) could equally well mean that the letters in pre precede the cursor in reverse order. If so, we obtain the text in the displayed editor like this:The function rev must consume a list of 1Strings and produce their reverse.
Both interpretations are fine choices, but it turns out that using the second one greatly simplifies the design of the program. The rest of this section demonstrates this point, illustrating the use of lists inside of structures at the same time. To appreciate the lesson properly, you should have solved the exercises in A Graphical Editor.
(add-at-end '() s)
Exercise 177. Design the function create-editor. The function consumes two strings and produces an Editor. The first string is the text to the left of the cursor and the second string is the text to the right of the cursor. The rest of the section relies on this function.
(check-expect (editor-kh (create-editor "" "") "e") (create-editor "e" "")) (check-expect (editor-kh (create-editor "cd" "fgh") "e") (create-editor "cde" "fgh"))
Before you read on, you should make up examples that illustrate how editor-kh works when you press the backspace ("\b") key to delete some letter, the "left" and "right" arrow keys to move the cursor, or some other arrow keys. In all cases, consider what should happen when the editor is empty, when the cursor is at the left end or right end of the non-empty string in the editor, and when it is in the middle. Even though you are not working with intervals here, it is still a good idea to develop examples for the “extreme” cases.
Once you have test cases, it is time to develop the template. In the case of editor-kh you are working with a function that consumes two complex forms of data: one is a structure containing lists, the other one is a large enumeration of strings. Generally speaking, the use of two complex inputs calls for a special look at the design recipe; but in cases like these, it is also clear that you should deal with one of the inputs first, namely, the keystroke.
(check-expect (editor-ins (make-editor '() '()) "e") (make-editor (cons "e" '()) '())) (check-expect (editor-ins (make-editor (cons "d" '()) (cons "f" (cons "g" '()))) "e") (make-editor (cons "e" (cons "d" '())) (cons "f" (cons "g" '()))))
At this point, you should do two things. First, run the tests for this function. Second, use the interpretation of Editor and explain abstractly why this function performs the insertion. And if this isn’t enough, you may wish to compare this simple definition with the one from exercise 84 and figure out why the other one needs an auxiliary function while our definition here doesn’t.
; Editor -> Editor ; moves the cursor position one 1String left, if possible (define (editor-lft ed) ed) ; Editor -> Editor ; moves the cursor position one 1String right, if possible (define (editor-rgt ed) ed) ; Editor -> Editor ; deletes one 1String to the left of the cursor, if possible (define (editor-del ed) ed)Again, it is critical that you work through a good range of examples.
(place-image/align (beside (text "pre" FONT-SIZE FONT-COLOR) CURSOR (text "post" FONT-SIZE FONT-COLOR)) 1 1 "left" "top" MT)
; Editor -> Image (define (editor-render e) (place-image/align (beside (editor-text (editor-pre e)) CURSOR (editor-text (editor-post e))) 1 1 "left" "top" MT))
(create-editor "pre" "post")
Exercise 180. Design editor-text. That is, use the standard design recipe and do not fall back on implode.
(define (editor-render ed) (place-image/align (beside (editor-text (reverse (editor-pre ed))) CURSOR (editor-text (editor-post ed))) 1 1 "left" "top" MT))
Note Modern applications allow users to position the cursor with the mouse (or other gesture-based devices). While it is in principle possible to add this capability to your editor, we wait with doing so until A Graphical Editor, with Mouse.
This last chapter of part II covers “design by composition.” By now you know that programs are complex products and that their production requires the design of many collaborating functions. This collaboration works well if the designer knows when to design several functions and how to compose these functions into one program.
You have encountered this need to design interrelated functions several times. Sometimes a problem statement implies several different tasks, and each task is best realized with a function. At other times, a data definition may refer to another one, and in that case, a function processing the former kind of data relies on a function processing the latter.
In this chapter, we present yet other scenarios that call for the design of many functions and their composition. To support this kind of work, the chapter presents some informal guidelines on divvying up functions and composing them. The next chapter then introduces some well-known examples whose solutions rely on the use of these guidelines and the design recipe in general. Since these examples demand complex forms of lists, however, this chapter starts with a section on a convenient way to write down complex lists.
12.1 The list Function
At this point, you should have tired of writing so many conses just to create a list, especially for lists that contain a bunch of values. Fortunately, we have an additional teaching language for you that provides mechanisms for simplifying this part of a programmer’s life. BSL+Yes, you have graduated from BSL. It is time to use the “Language” menu and to select the “Choose Language” entry. From now until further notice, use “Beginning Student Language with List Abbreviations” to work through the book. does so, too.
(list 0 1 2 3 4 5 6 7 8 9)
Exercise 181. Use list to construct the equivalent of the following lists:Start by determining how many items each list and each nested list contains. Use check-expect to express your answers; this ensures that your abbreviations are really the same as the long-hand.
Exercise 182. Use cons and '() to construct the equivalent of the following lists:Use check-expect to express your answers.
Exercise 183. On some occasions lists are formed with cons and list. Reformulate the following lists using cons and '() exclusively:
Use check-expect to express your answers.
Exercise 185. You know about first and rest from BSL, but BSL+ comes with even more selectors than that. Determine the values of the following expressions:
Formulate auxiliary function definitions for every dependency between quantities in the problem statement. In short, design one function per task.
Formulate auxiliary function definitions when one data definition points to a second data definition. Roughly, design one template per data definition.
If the composition of values requires knowledge of a particular domain of application—
for example, composing two (computer) images, accounting, music, or science— design an auxiliary function.
If the composition of values requires a case analysis of the available values—
for example, is a number positive, zero, or negative— use a cond expression. If the cond looks complex, design an auxiliary function whose inputs are the partial results and whose function body is the cond expression. Doing so separates out the case analysis from the recursive process.
If the composition of values must process an element from a self-referential data definition—
a list, a natural number, or something like those— design an auxiliary function.
If everything fails, you may need to design a more general function and define the main function as a specific use of the general function. This suggestion sounds counter-intuitive but it is called for in a remarkably large number of cases.
The last two criteria are situations that we haven’t discussed in any detail, though examples have come up before. The next two sections illustrate these principles with additional examples.
Maintain a list of function headers that must be designed to complete a program. Writing down complete function headers ensures that you can test those portions of the programs that you have finished, which is useful even though many tests will fail. Of course, when the wish list is empty, all tests should pass and all functions should be covered by tests.
People need to sort things all the time, and so do programs. Investment advisors sort portfolios by the profit each holding generates. Game programs sort lists of players according to scores. And mail programs sort messages according to date or sender or some other criteria.
Sample Problem: Design a function that sorts a list of (real) numbers.
; List-of-numbers -> List-of-numbers ; rearrange alon in descending order (check-expect (sort> '()) '()) (check-expect (sort> (list 12 20 -5)) (list 20 12 -5)) (check-expect (sort> (list 3 2 1)) (list 3 2 1)) (check-expect (sort> (list 1 2 3)) (list 3 2 1)) (define (sort> alon) alon)
Inserting a number into a sorted list clearly isn’t a simple task. It demands searching through the sorted list to find the proper place of the item. Searching through any list, however, demands an auxiliary function, because lists are of arbitrary size and, by hint 3 of the preceding section, processing values of arbitrary calls for the design of an auxiliary function.
; Number List-of-numbers -> List-of-numbers ; inserts n into the sorted list of numbers alon (define (insert n alon) alon)
Note what the development of examples teaches us. The insert function has to find the first number that is smaller than the given n. When there is no such number, the function eventually reaches the end of the list and it must add n to the end. Now, before we move on to the template, you should work out some additional examples. To do so, you may wish to use the supplementary examples for sort>.
To fill the gaps in the template of insert, we again proceed on a case-by-case basis. The first case concerns the empty list. According to the first example, (list n) is the expression needed in the first cond clause, because it constructs a sorted list from n and alon.
(insert 7 (list 6 5 4))
(insert 0 (list 6 2 1 -1))
If so, all the items in alon are smaller than n because alon is already sorted. The answer in that case is (cons n alon).
- If, however, n is smaller than (first alon), then the function has not yet found the proper place to insert n into alon. The first item of the result must be (first alon) and that n must be inserted into (rest alon). The final result in this case isbecause this list contains n and all items of alon in sorted order—
which is what we need.
Figure 49 contains the complete definitions of insert and sort>. Copy it into the definition area of DrRacket, add the test cases back in, and test the program. All tests should pass now and they should cover all expressions.
Terminology This particular program for sorting is known as insertion sort in the programming literature. Later we will study alternative ways to sort lists, using an entirely different design strategy.
; List-of-numbers -> List-of-numbers ; produces a sorted version of alon (define (sort> alon) (cond [(empty? alon) '()] [(cons? alon) (insert (first alon) (sort> (rest alon)))])) ; Number List-of-numbers -> List-of-numbers ; inserts n into the sorted list of numbers alon (define (insert n alon) (cond [(empty? alon) (cons n '())] [else (if (>= n (first alon)) (cons n alon) (cons (first alon) (insert n (rest alon))))]))
Exercise 186. Recall from Intermezzo: BSL that BSL comes with several different ways to formulate tests. One of them is check-satisfied, which determines whether an expression satisfies a certain property.Now consider this function definition:
; List-of-numbers -> List-of-numbers ; produces a sorted version of l (define (sort>/bad l) '(9 8 7 6 5 4 3 2 1 0))Can you formulate a test case that shows sort>/bad is not a sorting function? Can you use check-satisfied to formulate this test case?
Notes (1) What may surprise you here is that we define a function to create a test. In the real world, this step is common and, on occasion, you really need to design functions for tests—
with their own tests and all. (2) Formulating tests with check-satisfied is occasionally easier than using check-expect (or other forms), and it is also a bit more general. When the predicate completely describes the relationship between all possible inputs and outputs of a function, computer scientists speak of a specification. Specifying with lambda explains how to specific sort> completely.
(define-struct email [from date message]) ; A Email Message is a structure: ; (make-email String Number String) ; interpretation (make-email f d m) represents text m sent by ; f, d seconds after the beginning of timeAlso develop a program that sorts lists of email messages by name. To compare two strings alphabetically, use the string<? primitive.
(define-struct gp [name score]) ; A GamePlayer is a structure: ; (make-gp String Number) ; interpretation (make-gp p s) represents player p who scored ; a maximum of s points
It determines whether some number occurs in a list of numbers. The function may have to traverse the entire list to find out that the number of interest isn’t contained in the list.
Develop the function search-sorted, which determines whether a number occurs in a sorted list of numbers. The function must take advantage of the fact that the list is sorted.
Exercise 190. Design prefixes. The function consumes a list of 1Strings and produces the list of all prefixes. Recall that a list p is a prefix of l if p and l are the same up through all items in p. For example, (list 1 2 3) is a prefix of itself and (list 1 2 3 4).
Design the function suffixes, which consumes a list of 1Strings and produces all suffixes. A list s is a suffix of l if p and l are the same from the end, up through all items in s. For example, (list 2 3 4) is a suffix of itself and (list 1 2 3 4).
Auxiliary functions are also needed when a problem statement is too narrow. Conversely, it is common for programmers to generalize a given problem just a bit to simplify the solution process. When they discover the need for a generalized solution, they design an auxiliary function that solves the generalized problem and a main function that just calls this auxiliary function with special arguments.
Sample Problem: Design a program that renders a polygon into an empty 50 by 50 scene.
A polygon is a planar figure with at least three corners consecutively connected by three straight sides. And so on.
As the domain knowledge statement says, a polygon consists of at least three sides and that means at least three Posns. Thus the answer to our question is that representations of polygons should be lists of at least three Posns.
The point of this discussion is that a naively chosen data representation—
(define MT (empty-scene 50 50)) ; Polygon -> Image ; renders the given polygon p into MT (define (render-poly p) MT)
(check-expect (render-poly (list (make-posn 20 0) (make-posn 10 10) (make-posn 30 10))) (scene+line (scene+line (scene+line MT 20 0 10 10 "red") 10 10 30 10 "red") 30 10 20 0 "red"))
(check-expect (render-poly (list (make-posn 10 10) (make-posn 20 10) (make-posn 20 20) (make-posn 10 20))) (scene+line (scene+line (scene+line (scene+line MT 10 10 20 10 "red") 20 10 20 20 "red") 20 20 10 20 "red") 10 20 10 10 "red"))
In general, it is better to formulate conditions via built-in predicates and selectors than your own (recursive) functions. We will explain this remark in Intermezzo: The Cost of Computation.
Sixth and last, we must test the functions. You should add a test for render-line but for now you may just accept our correctness promise. In that case, testing immediately reveals flaws with the definition of render-poly; in particular, the test case for the square fails. On one hand, this is fortunate because it is the purpose of tests to find problems before they affect regular consumers. On the other hand, the flaw is unfortunate because we followed the design recipe, we made fairly regular decisions, and yet the function doesn’t work.
Before you give up hope in such a situation, you should experiment with the function in DrRacket’s interactions area. For our example, the results are illuminating. Here is the failing test case, with the input on the left and the output on the right:
As a matter of fact, one could also argue that render-polygon is really the function that connects the successive dots specified by a list of Posns and connects the first and the last Posn of the trailing triangle. If we don’t draw this last, extra line, render-polygon is just a “connects the dots” function. And as such, it almost solves our original problem; all that is left to do is to add a line from the first Posn to the last one in the given Polygon.
Put differently, the analysis of our failure suggests two ideas at once. First, we should solve a different, a more general looking problem. Second, we should use the solution for this generalized problem to solve the original one.
Sample Problem: Design a program that connects a bunch of dots.
(check-expect (connect-dots (list (make-posn 20 0) (make-posn 10 10) (make-posn 30 10))) (scene+line (scene+line MT 20 0 10 10 "red") 10 10 30 10 "red"))