关闭

练习 2.3 定义矩形

标签: sicp
113人阅读 评论(0) 收藏 举报
分类:

“` 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)
















0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7163次
    • 积分:720
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:7篇
    • 译文:27篇
    • 评论:0条