Thanks Rodolfo and Eli for the education, very elegant solutions.<div><br></div><div>I really like the clever use of the "(and (right-triangle? a b c) (list a b c))))" idiom.<br><div><br></div><div>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.</div>
<div><br></div><div>After going "D'oh" about the infinite loop, here is the code I ended up with:<div><div><br></div><div><div>(define (pythagorean-triple n)</div><div> (let loop-ab ([a 1] [b 2])</div><div>
(define c (- n a b))</div><div> (cond [(>= a n) '()]</div><div> [(<= c b) (loop-ab (add1 a) (+ a 2))]</div><div> [(right-triangle? a b c) (list a b c)]</div><div> [else (loop-ab a (add1 b))])))</div>
<div><br></div><div>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?</div><div><br>
</div><div>Thanks again!</div><div>-joe</div><div><br></div><div><br></div><br><div class="gmail_quote">On Sun, Mar 18, 2012 at 11:25 PM, Eli Barzilay <span dir="ltr"><<a href="mailto:eli@barzilay.org">eli@barzilay.org</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="im">20 minutes ago, Rodolfo Carvalho wrote:<br>
><br>
> (define (pythagorean-triple/alt n)<br>
> (for*/first ([a (in-range 1 n)]<br>
> [b (in-range a n)]<br>
> [c (in-value (- n a b))]<br>
> #:when (right-triangle? a b c))<br>
> (list a b c))) <br>
<br>
</div>You can also use `for*/or':<br>
<br>
(define (pythagorean-triple/alt n)<br>
(for*/or ([a (in-range 1 n)]<br>
[b (in-range a n)])<br>
(define c (- n a b))<br>
(and (right-triangle? a b c) (list a b c))))<br>
<span class="HOEnZb"><font color="#888888"><br>
--<br>
((lambda (x) (x x)) (lambda (x) (x x))) Eli Barzilay:<br>
<a href="http://barzilay.org/" target="_blank">http://barzilay.org/</a> Maze is Life!<br>
</font></span></blockquote></div><br></div></div></div></div>