Function template for output lists of known length

If the output from the function is a list of known length (e.g. you know in advance that it will be exactly 3 elements long), treat this as a "compound data type" above, except that instead of building a structure, you build a list using cons. For example,

;; three-copies: symbol => list of 3 symbols
;; Example: (three-copies 'bluebird) => (cons 'bluebird (cons 'bluebird (cons 'bluebird empty)))
(define (three-copies sym)
   (cons ... (cons ... (cons ... empty))))
Since the output is known to be a list of exactly three elements, the most likely way to build it is with three nested conses and an empty, as above. This template would of course be filled in as
;; three-copies: symbol => list of 3 symbols
;; Example: (three-copies 'bluebird) => (cons 'bluebird (cons 'bluebird (cons 'bluebird empty)))
(define (three-copies sym)
   (cons sym (cons sym (cons sym empty))))
An equivalent template, using list syntax, is
;; three-copies: symbol => list of 3 symbols
;; Example: (three-copies 'bluebird) => (cons 'bluebird (cons 'bluebird (cons 'bluebird empty)))
(define (three-copies sym)
   (list ... ... ...))
which would be filled in as
;; three-copies: symbol => list of 3 symbols
;; Example: (three-copies 'bluebird) => (cons 'bluebird (cons 'bluebird (cons 'bluebird empty)))
(define (three-copies sym)
   (list sym sym sym))

It's also possible, though less likely, that it'll be built from a single element and a pre-existing list one shorter, or from two elements and a pre-existing list two shorter, etc. For example, suppose we were writing a function which, given a list of 2 symbols, returns a list twice as long by repeating the given list. The obvious template is

;; stutter-list-2: list-of-2-symbols => list-of-4-symbols
;; Example: (stutter-list-2 (list 'a 'b)) => (list 'a 'b 'a 'b)
(define (stutter-list-2 list-of-2)
  (cons ... (cons ... (cons ... (cons ... empty)))))
and indeed the function could be written based on this template. But since we already have a list-of-2-symbols given to us, we could write it more simply as
;; stutter-list-2: list-of-2-symbols => list-of-4-symbols
;; Example: (stutter-list-2 (list 'a 'b)) => (list 'a 'b 'a 'b)
(define (stutter-list-2 list-of-2)
  (cons ... (cons ... list-of-2)))
The complete function definition would then be
;; stutter-list-2: list-of-2-symbols => list-of-4-symbols
;; Example: (stutter-list-2 (list 'a 'b)) => (list 'a 'b 'a 'b)
(define (stutter-list-2 list-of-2)
  (cons (first list-of-2 (cons (second list-of-2) list-of-2)))
Note how we've combined the input template for a fixed-length list (the parameter list-of-2) with the output template for a fixed-length list (the resulting list of 4).
Last modified: Thu Jan 20 10:33:01 EST 2000
Stephen Bloch / sbloch@adelphi.edu