title: Data Driven Templates description: > Notes on the Data driven template recipe. categories: posts
Table of Contents
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.
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.
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.
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.
| 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
.
one of
templateThis 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