[racket] Racket style question

From: Tim Brown (tim.brown at cityc.co.uk)
Date: Wed Mar 21 13:01:23 EDT 2012

Rodolfo,

I started Project Euler with nested (do ...) loops.
Which are beyond ugly. It was truly revolutionary
finding the for/... forms.

Get a hang of them!

Also, you might like to use:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define last-progress-ms #f)
;;; it's global, it's expeident, but it has worked for me so far!
(define (progress i period (max-i #f))
   (when (= (modulo i period) 0)
     (let* ((now-ms (current-milliseconds))
            (delta-raw (and last-progress-ms (- now-ms last-progress-ms)))
            (delta-s (and delta-raw (quotient delta-raw 1000)))
            (delta-ms (and delta-raw (remainder delta-raw 1000))))
       (set! last-progress-ms now-ms)
       (if
         max-i
         (and
           (printf "~a+~a:~a.~a|" i (- max-i i) delta-s delta-ms)
           (flush-output))
         (and (printf "~a:~a.~a|" (/ i period) delta-s delta-ms)
              (flush-output))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

It's useful in loops like:

(let ((stupid-number-youll-find-so-often-in-PE(expt 10 1034)))
(for*/first
   (
    [k (in-range 0 stupid-number-youll-find-so-often-in-PE)]
    #:when (progress (- stupid-number-youll-find-so-often-in-PE k) 1000000)
    [i (in-range 0 10)]
    [j (in-range 0 10)]
    ...)))

You'll know when you'll need it!
#:when (printf ...)
will become your friend!

Tim

Eli Barzilay wrote:
> 20 minutes ago, Rodolfo Carvalho wrote:
>>
>> (define (pythagorean-triple/alt n)
>>    (for*/first ([a (in-range 1 n)]
>>                 [b (in-range a n)]
>>                 [c (in-value (- n a b))]
>>                 #:when (right-triangle? a b c))
>>      (list a b c)))
>
> You can also use `for*/or':
>
>    (define (pythagorean-triple/alt n)
>      (for*/or ([a (in-range 1 n)]
>                [b (in-range a n)])
>        (define c (- n a b))
>        (and (right-triangle? a b c) (list a b c))))
>


-- 
Tim Brown <tim.brown at cityc.co.uk>  | City Computing Limited            |
T: +44 20 8770 2110                | City House, Sutton Park Road      |
F: +44 20 8770 2130                | Sutton, Surrey, SM1 2AE, GB       |
-----------------------------------------------------------------------|
BEAUTY:  What's in your eye when you have a bee in your hand           |
-----------------------------------------------------------------------'
City Computing Limited registered in London No. 1767817.
Registered Office: City House, Sutton Park Road, Sutton, Surrey, SM1 2AE
VAT number 372 8290 34.

Posted on the users mailing list.