Решение упражнения 2.2 из SICP

17 January, 2008 (20:24) | Решения упражнений

В этом упражнении нет каких-то подводных камней. Все достаточно прямолинейно и демонстрирует концепцию барьеров абстракций.

(define (make-segment start-point end-point) 
  (cons start-point end-point))
(define (start-point segment) 
  (car segment))
(define (end-point segment) 
  (cdr segment))
(define (make-point x y) 
  (cons x y))
(define (x-point point) 
  (car point))
(define (y-point point) 
  (cdr point))
(define (average a b) 
  (/ (+ a b) 2.0))
(define (midpoint-segment segment) 
  (make-point (average (x-point (start-point segment)) 
                       (x-point (end-point segment))) 
              (average (y-point (start-point segment)) 
                       (y-point (end-point segment)))))

Вот и всё.

Comments

Comment from Abra-kadabr
Date: January 6, 2016, 10:16 am

вроде координата средины отрезка вычесляется как половина разности между конецчной и начальной точкой а не как сумма

Comment from Irv
Date: January 20, 2016, 2:04 pm

(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))

(define (make-segment a b) (cons a b))
(define (start-segment s) (car s))
(define (end-segment s) (cdr s))

(define (mid-point s)
  (let ((a (start-segment s))
        (b (end-segment s)))
    (let ((x1 (x-point a))
          (x2 (x-point b))
          (y1 (y-point a))
          (y2 (y-point b)))
      (make-point
       (/ (+ x1 x2) 2)
       (/ (+ y1 y2) 2)))))

(mid-point
 (make-segment
  (make-point 1 1)
  (make-point 3 3)))

Write a comment