也没什么

迷失了方向

练习 2.3 定义矩形

“` lisp

lang racket

;: 练习2.3 定义矩形

;: 定义点
(define (make-point x y)
(cons x y))
(define (x-point point)
(car point))
(define (y-point point)
(cdr point))

(define (print-point p)
(newline)
(display “(“)
(display (x-point p))
(display “,”)
(display (y-point p))
(display “)”))

;: 计算给定矩型的周长和面积
;: 2 * (宽+高)
(define (perimeter-rect rect)
(* 2 (+ (width-rect rect) (height-rect rect))))
;: 宽*高
(define (area-rect rect)
(* (width-rect rect) (height-rect rect)))

;: 第一种表示法:用两个顶点表示,左上顶点,右下顶点
(define (make-rect pt0 pt1) (cons pt0 pt1))
(define (left-point rect) (car rect))
(define (right-point rect) (cdr rect))

;: 获取矩形的宽
(define (width-rect rect)
(let ((left (left-point rect))
(right (right-point rect)))
(- (x-point right) (x-point left))))

;: 获取矩形的高
(define (height-rect rect)
(let ((left (left-point rect))
(right (right-point rect)))
(- (y-point right) (y-point left))))

;: 制造一个矩型
(define rect (make-rect (make-point 1 2)
(make-point 3 4)))

;: 测试
rect
(area-rect rect)
(perimeter-rect rect)

lisp

lang racket

;: 练习2.3 定义矩形
;: 平面上线段的表示问题
(define (make-segment start-point end-point)
(cons start-point end-point))

(define (start-segment seg)
(car seg))
(define (end-segment seg)
(cdr seg))

;: 定义点
(define (make-point x y)
(cons x y))
(define (x-point point)
(car point))
(define (y-point point)
(cdr point))

;: 计算给定矩型的周长和面积
;: 2 * (宽+高)
(define (perimeter-rect rect)
(* 2 (+ (width-rect rect) (height-rect rect))))
;: 宽*高
(define (area-rect rect)
(* (width-rect rect) (height-rect rect)))

;: 第二种表示法:用两条相互垂真的线段表示
(define (make-rect line01 line02) (cons line01 line02))

;: 获取矩形的宽
(define (width-rect rect)
(let ((line (car rect)))
(abs (- (x-point (start-segment line)) (x-point (end-segment line))))))

;: 获取矩形的高
(define (height-rect rect)
(let ((line (cdr rect)))
(abs (- (y-point (start-segment line)) (y-point (end-segment line))))))

;: 制造一个矩型
(define rect (make-rect (make-segment (make-point 1 4) (make-point 3 4))
(make-segment (make-point 1 2) (make-point 1 4))
))

;: 测试
(area-rect rect)
(perimeter-rect rect)
















阅读更多
版权声明:知行合一 https://blog.csdn.net/yemeishenme/article/details/51547763
文章标签: sicp
想对作者说点什么? 我来说一句

类的概念矩形

2018年01月14日 1KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭