2015/10/10

SICP 問題 2.3

;; 長方形を高さと幅で定義
(define (make-rectangle height width)
  (cons height width))

(define (perimeter-rect rect)
  (+ (* 2 (height-rect rect))
     (* 2 (width-rect rect))))

(define (area-rect rect)
  (* (height-rect rect)
     (width-rect rect)))

(define (height-rect rect)
  (car rect))

(define (width-rect rect)
  (cdr rect))
gosh> (define r1 (make-rectangle 10 5))
r1
gosh> (perimeter-rect r1)
30
gosh> (area-rect r1)
50

 
 

;; 長方形を対角の二点によって定義
(define (make-rect p1 p2)
  (cons p1 p2))

(define (point-1 rect)
  (car rect))

(define (point-2 rect)
  (cdr rect))

(define (height-rect rect)
  (abs (- (y-point (point-1 rect))
          (y-point (point-2 rect)))))

(define (width-rect rect)
  (abs (- (x-point (point-1 rect))
          (x-point (point-2 rect)))))
gosh> (define r2 (make-rect (make-point 0 0) (make-point 10 5)))
r2
gosh> (perimeter-rect r2)
30
gosh> (area-rect r2)
50

© 2022 wat-aro