Guided Practice 6.4: Alternating Lists

There are two questions in this Guided Practice. The first is an easy exercise using the alternating lists as we have defined them. The second is intended to give you more insight into the nature of data definitions.

Question 1: Design a function lasn-number-of-strings that takes a lasn and returns the number of strings in the lasn.

[Solution to question 1]

Question 2: Our data definitions for lasn and lans make two assumptions:

If our intended application violates either of those assumptions, then we need to go back and re-do our data analysis accordingly.

For example, consider the following problem: Given an alternating list of strings and numbers, starting with a string, return true if each number is equal to the length of the string preceding it, and false otherwise. For example:

    (right-lengths? empty)
    (right-lengths? (list "foo" 3 "april" 5 "george" 6))
    (right-lengths? (list "foo" 3 "april" 4 "george" 6))
    (right-lengths? (list 3 "april" 4 "george" 6))
    "this should raise an error, because the argument is not a lasn"))

(check-error, defined in extras.rkt, passes if and only if its argument raises an error.)

Here both our assumptions are violated: we are only interested in LASNs, not LANSs, and we are very much interested in the relation between the strings and the numbers.

There's no obvious way to write this function using the tools we have and the data definition we gave in this lesson.

To represent the data in these examples, we might write the following data definition:

;; A LASI is one of:
;; -- empty
;; -- (cons String (cons Integer LASI))

Here we are calling these LASI's so there will be no confusion with LASN's.

Write out the template for LASI's, using this data definition, and write right-lengths? . Follow the template recipe. Notice that (cons String (cons Integer LASI)) is a "structured value."

[Solution to question 2]

Last modified: Fri Sep 4 11:50:26 Eastern Daylight Time 2015