[英]how to multiply the elements in two lists and save the result in a third list to return in scheme?
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我想将方案中 2 个列表的元素相乘,并将每个相乘的结果保存在由 function 返回的第三个列表中
and.. the lists will always have the same size并且..列表将始终具有相同的大小
The idea in python is this python 中的想法是这样的
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] =>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我也想做同样的事情,但是在 function 的计划中,我只有 3 天的学习计划
(def (multi-elements list1 list2)
....
)
any suggestions?有什么建议么?
The map
procedure can be used to map over multiple lists. map
过程可用于 map 在多个列表中。 The procedure that is given to map
should accept as many arguments as there are lists.提供给map
的过程应该接受与列表一样多的 arguments。 You can map over two lists using *
to get the result you are after:您可以使用*
在两个列表上 map 获得您想要的结果:
> (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:由于*
采用任意数量的 arguments,因此您也可以以相同的方式在三个(或更多)列表上使用 map:
> (map * '(1 2 3) '(2 3 4) '(2 2 2))
(4 12 24)
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:由于我们将 go 直到l1
用完并且不考虑 Python 版本中l2
的长度,我建议在 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.