CS 1102 (A12): Accelerated Intro to Program Design
Examples of Templates

Templates arise from data definitions. It's meaningless to talk about a template without a data definition. The idea of a template is to write a skeleton of a function that consumes a particular kind of data as input. The template captures everything we know about the structure of the program based on the structure of the data.

Template for Structures

;; A circle is (make-circle posn number)
(define-struct circle (center radius))

would have the template

#|
(define (circle-func a-circle)
   ...(circle-center a-circle)...
   ...(circle-radius a-circle)...
)
|#

Thus for a structure, the template simply selects all possible components. When you use the template, some selectors may not be needed.

Template for Union Type

;; A square is (make-square posn number)
(define-struct square (top-left width))
#|
(define (square-func a-square)
   ...(square-top-left a-square)...
   ...(square-width a-square)...
)
|#

;; A shape is either
;;  - a circle, or
;;  - a square

Here, the template for shape has two cases (one for each option in the definition). In each case, we call the "helper" template for the corresponding shape. (As you get more experienced, you may skip the separate template definitions for simple structure, such circle and square, and embed them directly in the mixed type template if needed).

#|
(define (shape-func a-shape)
  (cond [(circle? a-shape) (circ-func a-shape)]
        [(square? a-shape) (square-func a-shape)]))
|#

Template for Lists

;; A list-of-symbol is
;;  - empty, or
;;  - (cons symbol list-of-symbol)

Notice that the recursive call to los-fun below follows the "shape" of the recursive data definition of list-of-symbol above.

#|
(define (los-func a-los)
  (cond [(empty? a-los) ...]
        [(cons? a-los)
         ...(first a-los)...
         ...(los-func (rest a-los))...]))
|#