0

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?

Dieku
  • 3
  • 2
  • 1
    You will have problems assimilating Scheme based on your knowledge of Python. It is much better forgetting that you know an algol language and focus on learning to think in lisp. You don't learn a programming language in 3 days. You might learn a dialect of one you already know well, but not a new language. Eg. learning Spanish might be easy for one who knows French and Italian, but you cannot expect Finish to be based on how well you understood Spanish. – Sylwester Jun 03 '21 at 20:24

2 Answers2

2

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)
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
0

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)
rawrex
  • 4,044
  • 2
  • 8
  • 24