Comp 210 Lab 3: Data Definitions

Index: Simple data definitions,


Simple Data Definitions

In class we described a multi-step process for writing programs, based upon a data definition. Our example data definition was for a list of symbols:

A list_of_symbols is

Let's try another example that you'll need for your homework, natural numbers, i.e., a non-negative integer.

For now, we are rather pedantic about our multi-step programming process to ensure that you learn good programming skills. With practice, it becomes habit for you to think about all the necessary steps. Our process is

  1. Make your data definition(s).

    A natural_number is

  2. Make sample elements of your data. This should include at least one of each case of the data definition(s).

    For natural numbers, we have

  3. Make a program template for each data definition. In each template,

    1. perform a case analysis -- a function case for each data definition case,
    2. extract the available data, and
    3. identify natural recursion -- the function may be recursive whenever the data is recursive.
    In other words, this means looking at the shape of your input data and writing all of the potentially useful information about your function based only on this shape. A template does not include information about the meaning of the function, i.e., what it computes.

    Do this for functions on natural numbers. You should use the following two functions:

  4. Give the contract and description for each function.

    Do this step and the following ones for the following sample functions:

  5. Provide examples of what these functions should do. Presumably, this should use the sample data already listed. Remember that your examples should illustrate what should happen for each interesting case of each function.

  6. Write your program by filling in the templates.

  7. Test these functions, using the examples.

Try some other example kinds of data:

For the curious...

In the future, we'll talk about templates and functions using multiple "interesting" inputs (i.e., multiple inputs that we need to recur on). But can you generalize some of the above functions and write the following:

You can also generalize the following easily, but the most obvious generalization doesn't strictly follow the template: