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

From: Carl Eastlund (carl.eastlund at gmail.com)
Date: Sun May 10 10:25:06 EDT 2009

On Sun, May 10, 2009 at 8:49 AM, Stephen Bloch <sbloch at adelphi.edu> wrote:
>
> 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)))

With that contract and purpose, the function is easy.

;; word? : word -> boolean
(define (word? arg) true)

The contract specifies that your input *must* be a word, so the answer
is always the same.  If you want to write a predicate like empty?,
cons?, and so forth, you must use the contract Any -> Boolean.
Otherwise you can't sensibly ask this question any time you might not
already know the answer.

> 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.)

As I said, if the contract is Word -> Boolean, this simplifies even
further to a trivial function.  But if the contract is Any -> Boolean
as with most predicates, your last version will most definitely crash
on inputs such as 5, "hello", and (make-posn 100 200).  The use of
cons? before applying first and rest is critical.

-- 
Carl Eastlund


Posted on the users mailing list.