2014年3月6日木曜日

開発環境

計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.1(データ抽象入門)、2.1.2(抽象の壁)、問題 2.3を解いてみる。

その他参考書籍

問題 2.3

コード(BBEdit, Emacs)

sample.scm

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

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

;; 平面上の長方形の表現
;; 2点の長方形
;; 構成子
(define (make-rectangle bottom-left top-right)
  (cons bottom-left top-right))

;; 選択子
(define (bottom-left-rectangle rec)
  (car rec))

(define (top-right-rectangle rec)
  (cdr rec))

(define (width-rectangle rec)
  (abs (- (x-point (bottom-left-rectangle rec))
          (x-point (top-right-rectangle rec)))))

(define (height-rectangle rec)
  (abs (- (y-point (bottom-left-rectangle rec))
          (y-point (top-right-rectangle rec)))))

;; 抽象の壁--------------------------------------------------------------------
(define (perimeter-rectangle rec)
  (* 2
     (+ (width-rectangle rec)
        (height-rectangle rec))))

(define (area-rectangle rec)
  (* (width-rectangle rec)
     (height-rectangle rec)))

;; テスト
(define rec (make-rectangle (make-point 0 0)
                            (make-point 5 10)))

(print "周囲の長さ:" (perimeter-rectangle rec))
(print "面積:" (area-rectangle rec))

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

gosh> (load "./sample")
周囲の長さ:30
面積:50
#t
gosh> 

sample.scm

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

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

;; 2つの線分の長方形
(define (make-rectangle bottom-seg left-seg)
  (cons bottom-seg left-seg))

(define (bottom-seg-rectangle rec)
  (car rec))

(define (left-seg-rectangle rec)
  (cdr rec))

(define (width-rectangle rec)
  (let ((seg (bottom-seg-rectangle rec)))
    (abs (- (x-point (start-segment seg))
            (x-point (end-segment seg))))))

(define (height-rectangle rec)
  (let ((seg (left-seg-rectangle rec)))
    (abs (- (y-point (start-segment seg))
            (y-point (end-segment seg))))))

;; 以降は前の長方形の表現と変わらず
;; 抽象の壁--------------------------------------------------------------------
(define (perimeter-rectangle rec)
  (* 2
     (+ (width-rectangle rec)
        (height-rectangle rec))))

(define (area-rectangle rec)
  (* (width-rectangle rec)
     (height-rectangle rec)))

;; テスト
(define rec (make-rectangle (make-segment (make-point 0 0)
                                          (make-point 5 0))
                            (make-segment (make-point 0 0)
                                          (make-point 0 10))))

(print "周囲の長さ:" (perimeter-rectangle rec))
(print "面積:" (area-rectangle rec))

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

gosh> (load "./sample")
周囲の長さ:30
面積:50
#t
gosh>

0 コメント:

コメントを投稿