理系学生日記

おまえはいつまで学生気分なのか

忍者TOOLS

問題2-3

長方形の周囲の長さと面積を求めろっつーんですけれども、長方形をどう表現するかが問われてるっぽいので、まずは2つの点で定義する方法をつかってみます。

(define (make-point x y)
  (cons x y))

(define (x-point point)
  (car point))

(define (y-point point)
  (cdr point))

(define (print-point point)
  (newline)
  (display "(")
  (display (x-point point))
  (display ",")
  (display (y-point point))
  (display ")"))

(define (make-rectangle left-up right-down)
  (cons left-up right-down))

(define (left-up-point rect)
  (car rect))

(define (right-down-point rect)
  (cdr rect))

そしてこんなやつ定義したら、周囲の長さと面積が求められる。

(define (area rect)
  (let ((vertical (abs (- (y-point (left-up-point rect))
			  (y-point (right-down-point rect)))))
	(horizontal (abs (- (x-point (right-down-point rect))
			    (x-point (left-up-point rect))))))
    (* vertical horizontal)))

(define (perimeter rect)
  (let ((vertical (abs (- (y-point (left-up-point rect))
			  (y-point (right-down-point rect)))))
	(horizontal (abs (- (x-point (right-down-point rect))
			    (x-point (left-up-point rect))))))
    (* 2 (+ vertical horizontal))))