2015年5月3日日曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.2(階層データ構造と閉包性)、2.2.3(公認インターフェースとしての並び)、写像の入れ子、問題2.40.を解いてみる。

その他参考書籍

問題2.40.

コード(BBEdit, Emacs)

(define square (lambda (x) (* x x)))
(define map
  (lambda (proc items)
    (if (null? items)
        '()
        (cons (proc (car items))
              (map proc (cdr items))))))
(define enumerate-interval
  (lambda (low high)
    (if (< high low)
        '()
        (cons low
              (enumerate-interval (+ low 1) high)))))
(define filter
  (lambda (predicate sequence)
    (cond ((null? sequence) '())
          ((predicate (car sequence))
           (cons (car sequence)
                 (filter predicate (cdr sequence))))
          (else (filter predicate (cdr sequence))))))

(define accumulate
  (lambda (op initial sequence)
    (if (null? sequence)
        initial
        (op (car sequence)
            (accumulate op initial (cdr sequence))))))

(define flatmap
  (lambda (proc seq)
    (accumulate append '() (map proc seq))))

(define unique-pairs
  (lambda (n)
    (flatmap (lambda (i)
               (map (lambda (j) (list i j))
                    (enumerate-interval 1 (- i 1))))
             (enumerate-interval 1 n))))

(define prime? (lambda (n) (= n (smallest-divisor n))))
(define smallest-divisor (lambda (n) (find-divisor n 2)))
(define find-divisor
  (lambda (n test-divisor)
    (cond ((< n (square test-divisor)) n)
          ((divides? test-divisor n) test-divisor)
          (else (find-divisor n (inc test-divisor))))))
(define divides? (lambda (a b) (= (remainder b a) 0)))
(define inc (lambda (n) (+ n 1)))

(define prime-sum?
  (lambda (pair)
    (prime? (+ (car pair)
               (cadr pair)))))

(define prime-sum-pairs
  (lambda (n)
    (filter prime-sum?
            (unique-pairs n))))
(prime-sum-pairs 6)

入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))

$ kscheme < sample40.scm
kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> kscm> ((2 1) (3 2) (4 1) (4 3) (5 2) (6 1) (6 5))
kscm> $

0 コメント:

コメントを投稿