Function template for functions whose value is a list of unknown length

If the function is to return a list of unknown length, combine the "several possible cases" template with the "list of known length" template.

Data definition:
a list-of-unknown-length is either
  1. empty , or
  2. (cons something some-other-list-of-unknown-length)
so the body will be a cond with two cases:
(define (function-returning-list arg1 arg2 arg3)
   (cond [... empty]
         [... (cons ... ...)]))
(As usual, the order of clauses may be different from this, but 95% of the time you want the simplest return value, empty, to appear in the first clause.)

Furthermore, if you're returning a cons, you'll be building it from a single element and another list, so you can expand the template to

(define (function-returning-list arg1 arg2 arg3)
   (cond [... empty]
         [... (cons some-element some-list)]))
Where you get some-element and some-list depends on their types. First, some-element has to be of the element type of the list (e.g. if the function is to return a list of numbers, some-element must be a number). More interestingly, some-list will be the same kind of list that function-returning-list is supposed to return, so 90% of the time that's where you'll get it:
(define (function-returning-list arg1 arg2 arg3)
   (cond [... empty]
         [... (cons some-element
                    (function-returning-list new-arg1 new-arg2 new-arg3))]))

Lists of (partially) unknown length

Sometimes you'll write a function that returns a list about whose length you know something, e.g. it'll never be empty, but it might be as short as one element. In this case empty doesn't make sense as the "simple-case" answer, but rather a one-element list:
(define (function-returning-non-empty-list arg1 arg2 arg3)
   (cond [... (cons some-element empty)]
         [... (cons some-element
                    (function-returning-non-empty-list new-arg1 new-arg2 new-arg3))]))

This template can help you to spot missing cases. If your function is supposed to return a potentially-empty list, but none of the cond-clauses returns empty, there's something wrong with your program. If your function is supposed to return a list longer than its argument, but none of the cond-clauses uses cons (or append or functions like that), there's something wrong with your program.


Last modified: Thu Jan 20 11:22:54 EST 2000
Stephen Bloch / sbloch@adelphi.edu