[BULK] [plt-scheme] 12.4.2 word definition; is this OK?

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Sun May 10 08:49:50 EDT 2009

On May 10, 2009, at 8:04 AM, Grant Rettke wrote:

> Is this definition of word OK?
>
> ;; A word is a list of 0 or more symbols ('a, 'b, ..., 'z).
>
> (check-expect empty (list))
>
> ;; word? : word -> boolean
> ;; to determine whether the argument is a word
> (define (word? arg)
>   (cond ((empty? arg) true)
>         ((symbol? (first arg)) (word? (rest arg)))
>         (else false)))

Yes, that sounds reasonable, with the caveat that Marco posted.   
However, "else false" always bugs me.  Rewriting your definition  
according to the structure (either empty or (cons symbol word)), I get

(define (word? arg)
    (cond ((empty? arg) true)
               ((cons? arg) (and (symbol? (first arg)) (word? (rest  
arg))))))

If you wish, you can rewrite this even shorter as

(define (word? arg)
    (or (empty? arg)
          (and (symbol? (first arg)) (word? (rest arg)))))

although this doesn't make the "empty?/cons?" bifurcation so obvious.

(Note: this definition is guaranteed not to crash because of the  
"short-circuit evaluation" of "or" in Scheme, and in many other  
languages like Java.  If you're teaching a class and don't want to  
bring up that issue yet, stick with my first definition above.)

Stephen Bloch
sbloch at adelphi.edu





Posted on the users mailing list.