[racket] Racket style question

From: Joe Gilray (jgilray at gmail.com)
Date: Mon Mar 19 00:44:39 EDT 2012

Hi, I created the following code from some scheme I found on
ProjectEuler.net (problem #9):

(define (right-triangle? a b c)
  (= (+ (* a a) (* b b)) (* c c)))

(define (pythagorean-triple n)
  (let loop-a ([a 1])
    (let loop-b ([b (add1 a)])
      (let ([c (- n a b)])
        (if (<= c b)
            (loop-a (add1 a))
            (if (right-triangle? a b c)
                (list a b c)
                (loop-b (add1 b)))))))

Is the following a better way to write this?

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

I wish I could do "(let* loop-ab ([a 1] [b (add1 a)])...", but that is not
allowed. In any event, this second version of pythagorean-triple feels a
little better than the original to me.  Of course taking the next step,
feels like going too far as it makes the relationship between n, c, a & b
harder to see:

(define (pythagorean-triple n)
  (let loop-abc ([a 1] [b 2] [c (- n 3)])
      (if (<= c b)
          (loop-abc (add1 a) (+ a 2) (- n (+ 3 (* a 2))))
          (if (right-triangle? a b c)
              (list a b c)
              (loop-abc a (add1 b) (- n (+ a (add1 b))))))))

Thoughts?

-joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120318/1fb482e4/attachment.html>

Posted on the users mailing list.