[racket] Fun with math lib - named let

From: Joe Gilray (jgilray at gmail.com)
Date: Sat Feb 23 20:42:17 EST 2013

Just had some fun using the new math library to solve ProjectEuler problems
#108 and #110.

Here's one of my functions:

; function which solves for the lowest number which has more than the
passed number of diophantine reciprocals
; n is multiplied by 2 to account for symmetrical (equivalent) solutions

(define (min-diophantine-recip n)
  (define limit (* 2 n))
  (define (findmax)  ; find the largest candidate that meets the criteria
    (let maxlp ([p 2] [prod 1])
      (if (> (num-diophantine-reciprocals (factorize prod)) limit) prod
(maxlp (next-prime p) (* p prod)))))

  (let lp ([max (findmax)])  ; strip off highest prime factor then search
for a smaller possibility
    (let* ([lst (factorize max)] [l (take lst (sub1 (length lst)))]
[multlim (first (last lst))])
      (let inclp ([cmult 2])
        (if (>= cmult multlim) max  ; found the answer
            (let ([newmax (* cmult (defactorize l))])
              (if (> (num-diophantine-reciprocals (factorize newmax)) limit)
                  (lp newmax)  ; found a smaller answer, iterate
                  (inclp (add1 cmult)))))))))

It utilizes factorize and defactorize from the math library - very useful.

I absolutely love writing racket code, the named let especially allows so
much freedom of expression.  Do functional purists find it easier to use
helper functions?  Maybe because I come from an "imperative" background,
the named let feels more natural to me.

In case you want to try out the problem, I'll let you write
(num-diophantine-reciprocals lst) yourself, good luck, it's a bit of a
challenge.

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

Posted on the users mailing list.