[plt-scheme] HtDP Section 14: stricter typing for eye color?

From: Joe Marshall (jrm at ccs.neu.edu)
Date: Tue Feb 17 10:31:20 EST 2004

Terrence Brannon <metaperl at urth.org> writes:

> The reason I asked is that I figured that a student of mine might ask me how and/or why anything is allowed in the eye-color slot and I wanted to be able to give them an authoritative answer, as well as put my mind to rest that Scheme is a good language to become religious about in my search for The One Perfect Language. 

There is no `One Perfect Language'.  You should not be religious about
*any* language, there are perfectly rational reasons to choose one
language over another. 

For the specific problem of ensuring that the `eye color' field
contains a valid eye color there are many solutions.   The easiest
one is to place an abstraction layer over the `raw' structure:

(define (carefully-set-eye-color! person new-color)
  (if (member new-color '(green blue brown glass))
      (set-eye-color! person new-color)
      (error "Color must be one of green blue or brown.")))

This is the essence of a dynamic check:  you ensure that every state
change is valid before you perform it.

Another is to create only those setters that set the eye color to a
valid value:

(define (set-eye-color-to-green! person)
  (set-eye-color! person 'green))

This is the essence of a static check:  you ensure that no code exists
that can perform an invalid state change.



Posted on the users mailing list.