[racket] syntax, differently
On Sun, Aug 1, 2010 at 7:45 PM, Marco Morazan <morazanm at gmail.com> wrote:
>> I'd also like to push for earlier introduction of (local ...) in
>> HtDP/2e. We all know that code duplication is a bad thing and that
>> giving complex constructs names is one of the easiest forms of
>> abstraction, but we can't use local definitions to handle these cases
>> until we've already done a lot of really complicated stuff. I'd like
>> to be able to contrast:
>>
>> (define (distance p1 p2)
>> (sqrt (+ (sqr (- (posn-x p1) (posn-x p2)))
>> (sqr (- (posn-y p1) (posn-y p2))))))
>>
>> and
>>
>> (define (distance p1 p2)
>> (local
>> [(define x1 (posn-x p1))
>> (define y1 (posn-y p1))
>> (define x2 (posn-x p2))
>> (define y2 (posn-y p2))]
>> (sqrt (+ (sqr (- x1 x2)) (sqr (- y1 y2))))))
>>
>> fairly early, so that I can emphasize that, while the first has fewer
>> keystrokes, the latter is easier for most people to read.
>>
>
> (define (distance p1 p2) (distance-helper (posn-x p1) (posn-y p1)
> (posn-x p2) (posn-y p2)))
>
> (define (distance-helper x1 y1 x2 y2) (sqrt (+ (sqr (- x1 x2)) (sqr (-
> y1 y2)))))
>
> What exactly does local contribute here? I am not convinced that more
> syntax and the thorny-for-students semantics of local is really what
> is needed.
>
That's always the trade-off. In a language with typing and
overloading, you could define two distance functions, one that takes
two posns and another that takes four numbers, and I think this would
be the most natural way to write distance.
But do we really want to have to introduce another function just to
make the naming prettier? Alternatively, do we really want to have to
introduce another piece of syntax just to make the naming prettier?
Both approaches have negatives.
I guess I lean toward providing a way for students to name parts
earlier, just because I think it helps them organize their thoughts.
Of course, too many of my Racket functions seem to be of the form
(define (blah ...)
(let ([x ...]
[y ...]
[z ...])
(foo x (+ y z)))
Maybe I'm backwards-projecting my (possibly non-idiomatic and
mis-directed) style on my beginning students.
Todd