Data Driven Templates

Table of Contents

Intro

Templates show the core structure that a function must have. Its structure is independent of the details of its definition.

In many cases, the template for a function is determined by the type of data the function consumes, here are some useful templates designed according to the data they are supposed to handle.

General Structure

For a given type TypeName the data driven template is:

(define (fn-for-type-name param)
  <body>)

Where param is the parameter, and the <body> is determined according to the table below.

Body Structure

Atomic Non-Distinct Data

Type of param/data cond Question Body or cond Answer
Number (number? param) (... param) Expression that operates on param
String (string? param)  
Boolean (boolean? param)  
Image (image? param)  
Interval Number[0, 10] (and (<= 0 param)
……….(< param 10))
 

etc.

Atomic Distinct Value

Type of param/data cond Question Body or cond Answer
"red" (string=? param "red") (...) Since value is distinct param disappears
false (false? param)  
empty (empty? param)  

etc.

One-of Data

Type of param/data Body Description
enumerations (cond [Q1 A1]
……….[Q2 A2])
Conditional with one clause per subclass of one of
itemizations    

Each question and answer expression is formed by following the rule in the question or answer column in the tables above. It is ok to use else for the last question for itemizations and large enumerations. Normal enumerations should not use else.

Sample one of template

This is how you would put together a Data definition using the ‘how to design data’ and ‘data driven templates’ recipes.

Clock is a one of type with two subclasses (one of which is not distinct making it an itemization).

;; Clock is one of:
;;  - Natural
;;  - false

The one of rule tells us to use cond, which needs one clause for each subclass of the itemization.

(define (fn-for-clock c)
  (cond [Q A]
        [Q A]))

;; Template rules used:
;;  - one of: 2 cases

The cond questions need to identify each subclass of data. The answers, need to follow templating rules for those subclasses data.

(define (fn-for-clock c)
  (cond [(number? c) (... c)]
        [Q A]))

;; Template rules used:
;;  - one of: 2 cases
;;  - atomic non-distinct: Natural

The second case is an atomic distinct type. Since it’s also the last case we can use else for the question.

(define (fn-for-clock c)
  (cond [(number? c) (... c)]
        [else (...)]))

;; Template rules used:
;;  - one of: 2 cases
;;  - atomic non-distinct: Natural
;;  - atomic distinct: false