【问题标题】:How to add two lists' elements together into a single list in Scheme?如何将两个列表的元素一起添加到 Scheme 中的单个列表中?
【发布时间】:2019-10-02 01:11:34
【问题描述】:

我正在研究 Scheme 的基础知识,需要找到一种方法将两个列表的元素 (x1 + x2, y1 + y2, z1 + z2) 添加到一个列表中,使其变为 (x3, y3, z3 )!

我发现要减去两个列表的元素,我可以使用“remove”关键字,将 list2 元素添加到 list1 我可以使用“append”,是否有类似的东西可以将实际元素添加在一起?

这是我目前所拥有的:

(define (my-vector x y z) (list x y z ))

(define first-vector '(1 2 3))

(define second-vector '(4 5 6))

first-vector

second-vector

(define (get-x1 first-vector)(car first-vector))
(define (get-y1 first-vector)(car (cdr first-vector)))
(define (get-z1 first-vector)(car (cdr (cdr first-vector))))

(define (get-x2 second-vector)(car second-vector))
(define (get-y2 second-vector)(car (cdr second-vector)))
(define (get-z2 second-vector)(car (cdr (cdr second-vector))))

(define (combine-vectors first-vector second-vector)
  (if (null? first-vector)
      second-vector
      (cons (car first-vector)
        (combine-vectors (cdr first-vector) second-vector))))


(define combined-vectors (combine-vectors first-vector second-vector))

combined-vectors

(define subtract-vectors (remove '(first-vector) second-vector))

(+ (get-x1 first-vector) (get-x2 second-vector))
(+ (get-y1 first-vector) (get-y2 second-vector))
(+ (get-z1 first-vector) (get-z2 second-vector))

输出当前是

(list 1 2 3)
(list 4 5 6)
(list 1 2 3 4 5 6)
5
7
9

我想要 5 7 9 阅读(列表 5 7 9)!提前感谢您的帮助:)

【问题讨论】:

  • (map + (list 1 2 3) (list 4 5 6)) = (list 5 7 9)
  • 除了重命名局部变量,get-x1 和 get-x2 有什么区别?

标签: list scheme racket


【解决方案1】:

正如 Alex 在 cmets 中提到的,map 是您这里最好的朋友。次要评论:您正在使用 lists,而不是矢量:

(define (add-lists l1 l2)
  (map + l1 l2))

一个冗长而无聊的替代方法是手动执行相同的迭代和处理,应用标准模式来遍历列表并构建输出列表,稍作修改,我们将在两个以上同时进行列表:

(define (add-lists l1 l2)
  (if (or (null? l1) (null? l2))
      '()
      (cons (+ (car l1) (car l2))
            (add-lists (cdr l1) (cdr l2)))))

无论哪种方式,它都按预期工作:

(define first-list '(1 2 3))
(define second-list '(4 5 6))

(add-lists first-list second-list)
=> '(5 7 9)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2023-01-13
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多