[plt-scheme] horay(?) to me!
> Ok, so many people here have been doing this a long time.
> I'm starting to understand scheme, loops, and quasiquoting.
> For no practical purpose at all I submit the following.
Hi Mike,
Small comments on the toy code:
> (let loop ((running #t))
> (let ((r (random 20)))
> (set! running (< r 17))
The *running* variable here doesn't have to be part of the loop's
iteration. In fact, the code recomputes it anyway! A slightly cleaner
version of the above might look something like this:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let loop ()
(let* ([r (random 20)]
[running (< r 17)])
...))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
We use the let* form to tell people reading the code that *running* will
be influenced by *r*. We can avoid the use of set! altogether.
I'm also using boxy brackets to visually set off the let-values a little
better, plus it appears to help catch off-by-one paren-balancing bugs in
my own code. It's the style advocated by the HTDP folks, and I'm liking
it a lot.
> (printf "r=~a running=~a~%" (number->string r) (if running "true" "false"))
> (printf "thread=~a~%"
> (thread
> (eval
> `(lambda () (sleep (random 4))
> (printf "thread count=~a~%" ,r)))))
> ;(sleep 2)
The eval/quasiquotation here is unnecessary, but you know that already.
*wink*
> (if running
> (begin
> ;(sleep 2)
> (loop running)))))
A "one-armed" if like this can be written using the *when* form:
(when running
; (sleep 2)
(loop running))
This *when* form comes with an implicit *begin*, so it's a little cleaner
in situations like this. It also hints to the reader that what's inside
is being done for side-effects rather than for its value.
Best of wishes!