简体   繁体   中英

How to add two lists' elements together into a single list in Scheme?

I'm working on the basics of Scheme and need to find a way to add two lists' elements together (x1 + x2, y1 + y2, z1 + z2) into one list so it becomes (x3, y3, z3)!

I've figured out that to subtract the two lists' elements I can use the "remove" keyword, and to add list2 elements to list1 I can use "append" is there something similar to add the actual elements together?

Here's what I have so far:

(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))

the output is currently

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

I want 5 7 9 to read (list 5 7 9): Thanks for any help in advance :)

As mentioned by Alex in the comments, map is your best friend here. Minor comment: you're working with lists , not with vectors:

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

A long and boring alternative would be to do the same iteration and processing by hand, applying the standard patter for traversing a list and building an output list, with the small modification that we'll do it at the same time over two lists:

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

Either way, it works as expected:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM