2015年5月1日金曜日

開発環境

計算機プログラムの構造と解釈[第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.39.を解いてみる。

その他参考書籍

問題2.39.

コード(BBEdit, Emacs)

(define append
  (lambda (list1 list2)
    (if (null? list1)
        list2
        (cons (car list1)
              (append (cdr list1) list2)))))

(define fold-right
  (lambda (op initial sequence)
    (if (null? sequence)
        initial
        (op (car (sequence))
            (fold-right op initial (cdr sequence))))))

(define fold-left
  (lambda (op initial sequence)
    (define iter
      (lambda (result rest)
        (if (null? rest)
            result
            (iter (op result
                      (car rest))
                  (cdr rest)))))
    (iter initial sequence)))

(define reverse1
  (lambda (sequence)
    (fold-right (lambda (x y)
                  (append y (list x)))
                '()
                sequence)))

(define reverse2
  (lambda (sequence)
    (fold-left (lambda (x y)
                 (cons y x))
               '()
               sequence)))

(begin (newline)
       (display (reverse1 '(1 2 3 4 5)))
       (newline)
       (display (reverse2 '(1 2 3 4 5)))
       (newline))

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

$ kscheme  < sample39.scm
kscm> kscm> kscm> kscm> kscm> kscm> 
(5 4 3 2 1)
(5 4 3 2 1)
#<undefined>
kscm> $

0 コメント:

コメントを投稿