2014年4月12日土曜日

開発環境

計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.2(階層データ構造と閉包性)、2.2.4(例: 図形言語)、フレーム、問題 2.46.を解いてみる。

その他参考書籍

問題 2.46.

コード(BBEdit, Emacs)

sample.scm

#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-

;; これまでに書いた手続き
(load "./procedures.scm")

(define (make-vect x y)
  (list x y))

(define (xcor-vect v)
  (car v))

(define (ycor-vect v)
  (car (cdr v)))

(define (add-vect v1 v2)
  (let ((x1 (xcor-vect v1))
        (y1 (ycor-vect v1))
        (x2 (xcor-vect v2))
        (y2 (ycor-vect v2)))
    (make-vect (+ x1 x2)
               (+ y1 y2))))

(define (sub-vect v1 v2)
  (let ((x1 (xcor-vect v1))
        (y1 (ycor-vect v1))
        (x2 (xcor-vect v2))
        (y2 (ycor-vect v2)))
    (make-vect (- x1 x2)
               (- y1 y2))))

(define (scale-vect s v)
  (make-vect (* s
                (xcor-vect v))
             (* s
                (ycor-vect v))))

(define v1 (make-vect 0 0))
(define v2 (make-vect 1 1))
(define v3 (make-vect 2 3))
(define v4 (make-vect 4 5))
(define s 100)
(define vectors (list v1 v2 v3 v4))
(define vectors-pairs (flatmap (lambda (v1)
                                 (map (lambda (v2)
                                        (cons v1 v2))
                                      vectors))
                               vectors))
                             
(for-each (lambda (vector-pair)
            (let ((v1 (car vector-pair))
                  (v2 (cdr vector-pair)))
              (print v1 " + " v2 " = " (add-vect v1 v2))))
          vectors-pairs)

(for-each (lambda (vector-pair)
            (let ((v1 (car vector-pair))
                  (v2 (cdr vector-pair)))
              (print v1 " - " v2 " = " (sub-vect v1 v2))))
          vectors-pairs)

(for-each (lambda (v)
            (print s "・" v " = " (scale-vect s v)))
          vectors)

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

$ ./sample.scm
(0 0) + (0 0) = (0 0)
(0 0) + (1 1) = (1 1)
(0 0) + (2 3) = (2 3)
(0 0) + (4 5) = (4 5)
(1 1) + (0 0) = (1 1)
(1 1) + (1 1) = (2 2)
(1 1) + (2 3) = (3 4)
(1 1) + (4 5) = (5 6)
(2 3) + (0 0) = (2 3)
(2 3) + (1 1) = (3 4)
(2 3) + (2 3) = (4 6)
(2 3) + (4 5) = (6 8)
(4 5) + (0 0) = (4 5)
(4 5) + (1 1) = (5 6)
(4 5) + (2 3) = (6 8)
(4 5) + (4 5) = (8 10)
(0 0) - (0 0) = (0 0)
(0 0) - (1 1) = (-1 -1)
(0 0) - (2 3) = (-2 -3)
(0 0) - (4 5) = (-4 -5)
(1 1) - (0 0) = (1 1)
(1 1) - (1 1) = (0 0)
(1 1) - (2 3) = (-1 -2)
(1 1) - (4 5) = (-3 -4)
(2 3) - (0 0) = (2 3)
(2 3) - (1 1) = (1 2)
(2 3) - (2 3) = (0 0)
(2 3) - (4 5) = (-2 -2)
(4 5) - (0 0) = (4 5)
(4 5) - (1 1) = (3 4)
(4 5) - (2 3) = (2 2)
(4 5) - (4 5) = (0 0)
100・(0 0) = (0 0)
100・(1 1) = (100 100)
100・(2 3) = (200 300)
100・(4 5) = (400 500)
$

0 コメント:

コメントを投稿