[plt-scheme] HtDP ex 11.2.4

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sat Feb 18 09:03:23 EST 2006

On Feb 18, 2006, at 3:33 AM, Richard Cleis wrote:

>> Another completely equivalent way is:
>>
>> (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".
>
> 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.

This is equivalent. The key is that the template is isomorphic to the 
data definition so that if you (or someone else) ever needs to go back 
and modify things, it's easy to know what corresponds to what. After 
all "modifying" things includes changing the data: deleting a clause, 
adding a clause, adding a field to a struct in  certain clause, 
deleting them, etc. My personal preference is to order the clauses in 
the cond/case/match in the same way as I order the clauses in the data 
def. I have come to nest conditionals almost always, rather than 
flattening out the cond. If I want a performance advantage (because I 
know or Matthew has told me how things work exactly), I may reorder the 
Data Def so that I can re-order the clauses in the 
cond/case/record-case/matchh etc.

Hope this makes sense. One day I intend to summarize the How to Design 
books in an compact "adult" version with reasoning as above. For now 
you need to infer this.

-- Matthias



Posted on the users mailing list.