[plt-scheme] Comprehension: An example with five nested loops and four guards

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Mon Jun 4 14:01:11 EDT 2007

An "real world" example from Project Euler. It features
five nested loops with four guards.

   The primes 3, 7, 109, and 673, are quite remarkable. By taking any
   two primes and concatenating them in any order the result will always
   be prime. For example, taking 7 and 109, both 7109 and 1097 are prime.
   The sum of these four primes, 792, represents the lowest sum for a
   set of four primes with this property.

   Find the lowest sum for a set of five primes for which any two primes
   concatenate to produce another prime.

; :primes ... and next-prime is in ec.ss.
; In prime? put an extra 0 or two on N, if you want
; more speed.

(require ec mzscheme)
(define N 10000)

(define (number-append x y)
     (number->string x) (number->string y))))

(first-ec 'not-found
           (:primes a 3 N)
           (:primes b (next-prime a) N)
           (if (and (prime? (number-append a b))
                    (prime? (number-append b a))))
           (:primes c (next-prime b) N)
           (if (and (prime? (number-append a c))
                    (prime? (number-append c a))
                    (prime? (number-append b c))
                    (prime? (number-append c b))))
           (:primes d (next-prime c) N)
           (if (and (prime? (number-append a d))
                    (prime? (number-append d a))
                    (prime? (number-append b d))
                    (prime? (number-append d b))
                    (prime? (number-append c d))
                    (prime? (number-append d c))))
           (:primes e (next-prime d) N)
           (if (and (prime? (number-append a e))
                    (prime? (number-append e a))
                    (prime? (number-append b e))
                    (prime? (number-append e b))
                    (prime? (number-append c e))
                    (prime? (number-append e c))
                    (prime? (number-append d e))
                    (prime? (number-append e d))))
           (list a b c d e))

/Jens Axel

Posted on the users mailing list.