[racket] Racket style question

From: Joe Gilray (jgilray at gmail.com)
Date: Mon Mar 19 03:35:35 EDT 2012

Thanks Rodolfo and Eli for the education, very elegant solutions.

I really like the clever use of the "(and (right-triangle? a b c) (list a b
c))))" idiom.

I had to look up in-value... unfortunately the manual is a bit sparse
there, but I got the gift by running some examples... thanks.

After going "D'oh" about the infinite loop, here is the code I ended up

(define (pythagorean-triple n)
  (let loop-ab ([a 1] [b 2])
    (define c (- n a b))
    (cond [(>= a n) '()]
          [(<= c b) (loop-ab (add1 a) (+ a 2))]
          [(right-triangle? a b c) (list a b c)]
          [else (loop-ab a (add1 b))])))

I noticed that the sequence-based solutions are quite a bit slower than the
code above probably because they don't short-cut on (<= c b), is there an
elegant way to speed them up?

Thanks again!

On Sun, Mar 18, 2012 at 11:25 PM, Eli Barzilay <eli at barzilay.org> 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))))
> --
>          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
>                    http://barzilay.org/                   Maze is Life!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120319/7d77897d/attachment.html>

Posted on the users mailing list.