how to multiply the elements in two lists and save the result in a third list to return in scheme?

225 views Asked by At

I want to multiply the elements of 2 lists in scheme and save the result of each multiplication in a third list that is returned by a function

and.. the lists will always have the same size

The idea in python is this

def multi_elements( l1, l2):
    save = []
    for i in range(len(l1)):
      save.append(l1[i] * l2[i])
    return save

a = [ 1, 2 ,3]
b = [ 2, 3 ,4]

c = multi_elements(a, b)

print("C= ",c)

=>C= [2, 6 ,12]

I want to do the same, but in scheme in a function called the same i only has 3 days learning scheme

(def (multi-elements list1 list2)
    ....
)

any suggestions?

2

There are 2 answers

0
rawrex On BEST ANSWER

Since we will go until the l1 is exhausted and with no regards to the length of the l2 in the Python version, I would suggest the following implementation in Scheme:

(define (multi-elements a b)
    (if (null? a)
        '() ;; We are at the end of the a list
        (cons (* (car a) (car b))  
              (multi-elements (cdr a) (cdr b)))))

For example:

(define x (list 1 2 3))
(define y (list 2 3 4))
(multi-elements x y)
;; Returns (2 6 12)
0
ad absurdum On

The map procedure can be used to map over multiple lists. The procedure that is given to map should accept as many arguments as there are lists. You can map over two lists using * to get the result you are after:

> (map * '(1 2 3) '(2 3 4))
(2 6 12)

Since * takes an arbitrary number of arguments, you could also map over three (or more) lists in the same way:

> (map * '(1 2 3) '(2 3 4) '(2 2 2))
(4 12 24)