Skip to content

Instantly share code, notes, and snippets.

@monmon
Created November 28, 2012 08:44
Show Gist options
  • Select an option

  • Save monmon/4159942 to your computer and use it in GitHub Desktop.

Select an option

Save monmon/4159942 to your computer and use it in GitHub Desktop.
SICP q2.40
; まずp.71-72で以下のことまでは学習済み
(define nil '())
(define (square x) (* x x))
(define (divides? a b)
(= (remainder b a) 0))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (prime? n)
(= n (smallest-divisor n)))
(define (enumerate-interval low high)
(if (> low high)
nil
(cons low (enumerate-interval (+ low 1) high))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
(define (prime-sum? pair)
(prime? (+ (car pair) (cadr pair))))
(define (make-pair-sum pair)
(list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
(define (prime-sum-pairs n)
(map make-pair-sum
(filter prime-sum?
(flatmap
(lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))))
; unique-pairsはp.71のaccumulateした対の並びそのもの、
; つまり、flatmapの部分なので
(define (unique-pairs n)
(flatmap
(lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))
(print (unique-pairs 4))
; ということで、flatmapの部分をunique-pairsに置き換えればOK
(define (prime-sum-pairs n)
(map make-pair-sum
(filter prime-sum?
(unique-pairs n))))
(print (prime-sum-pairs 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment