当前位置: 首页> 财经> 产业 > sicp每日一题[2.2]

sicp每日一题[2.2]

时间:2025/7/11 14:26:36来源:https://blog.csdn.net/ilongchaos/article/details/142016156 浏览次数:0次

Exercise 2.2

Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor m a k e − s e g m e n t make-segment makesegment and selectors s t a r t − s e g m e n t start-segment startsegment and e n d − s e g m e n t end-segment endsegment that define the representation of segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x x x coordinate and the y y y coordinate. Accordingly, specify a constructor m a k e − p o i n t make-point makepoint and selectors x − p o i n t x-point xpoint and $y-point $that define this representation. Finally, using your selectors and constructors, define a procedure m i d p o i n t − s e g m e n t midpoint-segment midpointsegment that takes a line segment as argument and returns its midpoint (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures, you’ll need a way to print points:

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

这道题目很简单,主要是为了检查我们是否理解了嵌套使用抽象数据结构的概念,有点像 Python 里的列表,每个列表元素也可以是列表。

(define (make-point x y)(cons x y))(define (x-point p) (car p))(define (y-point p) (cdr p))(define (make-segment start end)(cons start end))(define (start-segment segment)(car segment))(define (end-segment segment)(cdr segment)); 线段中点坐标就是起点和终点横纵坐标的平均值
(define (midpoint-segment segment)(let ((start (start-segment segment))(end (end-segment segment)))(make-point (average (x-point start) (x-point end))(average (y-point start) (y-point end))))); 设置线段起点为(3, 5),终点为(7, 7),中点应该为(5, 6)
(define start (make-point 3 5))
(define end (make-point 7 7))
(define line (make-segment start end))
(print-point (midpoint-segment line)); 执行结果
(5, 6)
关键字:sicp每日一题[2.2]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: