learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-40.scm (2059B)


      1 (define-library (sicp solutions chapter-2 exercise-40)
      2   (import (scheme base)
      3           (only (sicp utils)
      4                 accumulate
      5                 enumerate-interval
      6                 filter
      7                 flatmap)
      8           (only (sicp solutions chapter-1 exercise-21) prime?))
      9   (export my-prime-sum-pairs
     10           prime-sum-pairs
     11           remove
     12           unique-pairs)
     13 
     14   (begin
     15     (define (unique-pairs n)
     16       (flatmap (lambda (i)
     17                  (map (lambda (j)
     18                         (list i j))
     19                       (enumerate-interval 1 (- i 1))))
     20                (enumerate-interval 1 n)))
     21 
     22     (define (remove item sequence)
     23       (filter (lambda (x)
     24                 (not (equal? x
     25                              item)))
     26               sequence))
     27 
     28     (define (permutations s)
     29       (if (null? s)
     30           (list '())
     31           (flatmap (lambda (x)
     32                      (map (lambda (p)
     33                             (cons x p))
     34                           (permutations (remove x
     35                                                 s))))
     36                    s)))
     37 
     38     (define (f n)
     39       (accumulate
     40        append
     41        '()
     42        (map (lambda (i)
     43               (map (lambda (j)
     44                      (list i j))
     45                    (enumerate-interval 1 (- i 1))))
     46             (enumerate-interval 1 n))))
     47 
     48     (define (g n)
     49       (flatmap (lambda (x) x) (enumerate-interval 1 n)))
     50 
     51     (define (prime-sum? pair)
     52       (prime? (+ (car pair)
     53                  (cadr pair))))
     54 
     55     (define (make-pair-sum pair)
     56       (list (car pair)
     57             (cadr pair)
     58             (+ (car pair)
     59                (cadr pair))))
     60 
     61     (define (prime-sum-pairs n)
     62       (map make-pair-sum
     63            (filter
     64             prime-sum?
     65             (flatmap
     66              (lambda (i)
     67                (map (lambda (j)
     68                       (list i j))
     69                     (enumerate-interval 1 (- i 1))))
     70              (enumerate-interval 1 n)))))
     71 
     72     (define (my-prime-sum-pairs n)
     73       (map make-pair-sum
     74            (filter prime-sum?
     75                    (unique-pairs n))))))