Comp 210 Lab 3: Heterogeneous Lists

Heterogeneous lists are those that can contain different kinds of data, e.g., symbols or numbers.

Solution 1: Use the definition of symbol-or-number.

; A list of symbols or numbers (lo-sym+num) is either
;   - empty
;   - (cons f r)
;     where f is a symbol-or-number, r is a lo-sym+num

Solution 2: Have one case for each kind of item.

; A list of symbols or numbers (lo-sym+num) is either
;   - empty
;   - (cons f r)
;     where f is a symbol, r is a lo-sym+num
;   - (cons f r)
;     where f is a number, r is a lo-sym+num

When you develop programs, you should use the template corresponding to the definition you choose.

  1.      (define (f a-losn)
            (cond
               [(empty? a-losn) ...]
               [else          ...(first a-losn)...(f (rest a-losn))]))
         
    where f probably calls another function on (first a-losn) that consumes a symbol-or-number.

  2.      (define (f a-losn)
            (cons
               [(empty? a-losn)          ...]
               [(symbol? (first a-losn)) ...(first a-losn)...(f (rest a-losn))...]
               [(number? (first a-losn)) ...(first a-losn)...(f (rest a-losn))...]))
         
    The answers of the two last cases typically, but not necessarily, have the same recursive calls.

    (Note how, for brevity, we've written the two last tests to take advantage of the sequential evaluation of conditionals. We could have used, for example, (and (cons? a-losn) (symbol? (first a-losn))) instead.)

Which is better? Both are equivalent, so it is a matter of style. Use the first style when you consider the elements to be of some more general kind of data; use the second when you don't.