sicp每日一题[2.46]

Exercise 2.46

A two-dimensional vector v running from the origin to a point can be represented as a pair consisting of an x-coordinate and a y-coordinate. Implement a data abstraction for vectors
by giving a constructor make-vect and corresponding selectors xcor-vect and ycor-vect. In terms of your selectors and constructor, implement procedures add-vect, sub-vect, and
scale-vect that perform the operations vector addition, vector subtraction, and multiplying a vector by a scalar:

(x_1, y_1) + (x_2, y_2) = (x_1+x_2, y_1+y_2),
(x_1, y_1) - (x_2, y_2) = (x_1-x_2, y_1-y_2),
s (x, y) = (sx, sy).

这道题没啥说的,差不多是最简单的题目了。

(define (make-vect x y)
  (cons x y))

(define (xcor-vect vector)
  (car vector))

(define (ycor-vect vector)
  (cdr vector))

(define (add-vect v1 v2)
  (make-vect (+ (xcor-vect v1)
                (xcor-vect v2))
             (+ (ycor-vect v1)
                (ycor-vect v2))))

(define (sub-vect v1 v2)
  (make-vect (- (xcor-vect v1)
                (xcor-vect v2))
             (- (ycor-vect v1)
                (ycor-vect v2))))

(define (scale-vect s v)
  (make-vect (* s (xcor-vect v))
             (* s (ycor-vect v))))


(define v1 (make-vect 3 4))
(define v2 (make-vect -4 3))

(xcor-vect v1)
(ycor-vect v1)

(add-vect v1 v2)
(sub-vect v1 v2)

(scale-vect 0.2 (add-vect v1 v2))

; 执行结果
3
4
(mcons -1 7)
(mcons 7 1)
(mcons -0.2 1.4000000000000001)
posted @   再思即可  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示