[plt-scheme] HtDP ex 11.2.4

From: Stephen Bloch (sbloch at panther.adelphi.edu)
Date: Sun Feb 19 21:09:04 EST 2006

Somebody wrote:
>> (define (list-template a-list)
>>   (cond
>>     [(empty? a-list) ...]
>>     [(cons? a-list) ...]))
>>
>> If you wanted to be creative, you could then switch the order of the
>> clauses, and then even replace the (empty? a-list) with "else".

to which Richard Cleis replied:
>It is creativity that gives me pause.  If I deviate from the templates 
>to do something like this:
>
>(define (depth dl)
>   (cond ((cons? dl) (+ 1 (depth (first dl))))
>         (else 0)))
>
>then am I tempting smite from tail recursion gods, or is this 
>acceptable?  It is sometimes difficult to distinguish whether a 
>practice is intended to improve programming or is intended to improve 
>the operation of the language.

Since the data definition has a "symbol" clause and a "cons" clause, I
would think the most natural way to write it is
	(cond [(symbol? dl) ...]
	      [(cons? dl) ...])
This has two advantages over using "else": first, it more closely
resembles the data definition; and second, it crashes appropriately if
given something that isn't a legitimate deep-list.  I tell my students
that the best use for "else" is to catch illegal inputs, although it can
also be used if the last case really is provably true whenever none of
the previous cases being true.
                                                 Stephen Bloch
                                              sbloch at adelphi.edu
                                        Math/CS Dept, Adelphi University


Posted on the users mailing list.