Hi, I'm redoing the ProjectEuler problems to learn Racket (great fun!). Below are three solutions to PE#4. Which is most in the spirit of Racket? Of course, I'd love to see solutions that are more idiomatic too. Is there a better way that doesn't use "for" at all?<div>
<br></div><div>Thanks!</div><div>-Joe</div><div><br></div><div><div>; function that turns a positive integer into a list of digits (in reverse order)</div><div>; invoke as (listize 234511) or (set-count (list->set (listize 112342)))</div>
<div>(define (listize num)</div><div> (if (= num 0)</div><div> '()</div><div> (cons (remainder num 10) (listize (quotient num 10)))))</div><div><br></div><div>; function that returns #t if the passed number is palindromic</div>
<div>; invoke as (palindromic? n)</div><div>(define (palindromic? n)</div><div> (if (equal? (listize n) (reverse (listize n))) #t #f))</div><div>)</div></div><div><br></div><div><div>; ProjectEuler problem #4</div><div>(define (euler4a)</div>
<div> (let ([max 100000])</div><div> (for ([i (build-list 899 (lambda (x) (+ 100 x)))])</div><div> (for ([j (build-list (- 999 i) (lambda (y) (+ i y)))])</div><div> (let ([prod (* i j)])</div><div> (when (palindromic? prod)</div>
<div> (begin</div><div> (when (> prod max) (set! max prod))</div><div> (printf "~a * ~a = ~a~n" i j prod))))))</div><div> (printf "Max palindromic product is ~a~n" max)))</div>
<div><br></div><div>; ProjectEuler problem #4 using for*</div><div>(define (euler4b)</div><div> (let ([max 100000])</div><div> (for* ([i (build-list 899 (lambda (x) (+ 100 x)))]</div><div> [j (build-list 899 (lambda (y) (+ 100 y)))]</div>
<div> #:when (and (>= j i) (palindromic? (* i j))))</div><div> (let ([prod (* i j)])</div><div> (when (> prod max) (set! max prod))</div><div> (printf "~a * ~a = ~a~n" i j prod)))</div>
<div> (printf "Max palindromic product is ~a~n" max)))</div><div><br></div><div>; ProjectEuler problem #4 - a mix of 4a and 4b</div><div>(define (euler4c)</div><div> (let ([max 100000])</div><div> (for* ([i (build-list 899 (lambda (x) (+ 100 x)))]</div>
<div> [j (build-list (- 999 i) (lambda (y) (+ i y)))]</div><div> #:when (palindromic? (* i j)))</div><div> (let ([prod (* i j)])</div><div> (when (> prod max) (set! max prod))</div><div>
(printf "~a * ~a = ~a~n" i j prod)))</div><div> (printf "Max palindromic product is ~a~n" max)))</div></div>