页面

2013年7月22日星期一

SICP 2.2

;;util
(defun average (x y)
  (/ (+ x y) 2))
(defun double (x)
  (* 2 x))
(defun square (x)
  (* x x))


;;2.2
(defun make-segment (start-segment end-segment)
  (cons start-segment end-segment))
(defun start-segment (segment)
  (car segment))
(defun end-segment (segment)
  (second segment))
(defun make-point (x-point y-point)
  (cons x-point y-point))
(defun x-point (point)
  (car point))
(defun y-point (point)
  (second point))
(defun midpoint-segment (segment)
  (make-point (average (x-point (start-segment segment))
(x-point (end-segment segment)))
      (average (y-point (start-segment segment))
(y-point (end-segment segment)))))
(defun print-point (point)
  (format t "~&(~A ~A)"
 (x-point point)
 (y-point point)))


;;2.3
(defun perimeter (rectangle)
  (double (+ (a-length rectangle)
     (b-length rectangle))))
(defun area (rectangle)
  (* (a-length rectangle)
     (b-length rectangle)))
(defun distance (point-a point-b)
  (sqrt (+ (square (- (x-point point-a)
      (x-point point-b)))
   (square (- (y-point point-a)
      (y-point point-b))))))
   
;;one kind of rectangle: two vertical sides (((1 1) (1 3)) ((1 1) (2 1)))
(defun a-length (rectangle)
  (distance (start-segment (car rectangle))
    (end-segment (car rectangle))))
(defun b-length (rectangle)
  (distance (start-segment (second rectangle))
    (end-segment (second rectangle))))


;;another kind of rectangle: any three points
(defun a-length (rectangle)
  (min-element (lengths rectangle)))
(defun b-length (rectangle)
  (let ((l (lengths rectangle)))
    (min-element (remove (min-element l) l))))
(defun min-element-iter (list result)
        (dolist (e list result)
          (if (< e result)
           (setf result e))))
(defun min-element (list)
        (min-element-iter list (first list)))


没有评论:

发表评论