在Scheme编程中将列表的每个元素与另一个列表的每个元素相乘 [英] Multiplying each element of a list with each element of another list in Scheme programming

查看:103
本文介绍了在Scheme编程中将列表的每个元素与另一个列表的每个元素相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Scheme中执行以下操作:

i am trying to do the following in Scheme:

List<int> list = new List<int>();
List<int> list1 = new List<int>();
List<int> list2 = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list1.Add(2);
list1.Add(4);
list1.Add(6);
list1.Add(8);

for (int i = 0; i < list.Count; i++)
{
    for (int p = 0; p < list1.Count; p++)
    {
         list2.Add(list[i] * list1[p]);
    }
}

如上面的代码所示,

我试图将第一个列表的每个元素与第二个列表中的每个元素相乘.所以1 * 2、1 * 4、1 * 6、1 * 8,然后转到下一个元素2 * 2,2 * 4 ..等等.

as seen in the code above, I am trying to multiply each element of the first list with every element in the second list. So 1*2, 1*4, 1*6, 1*8, then going to the next element, 2*2,2*4.. etc.

我无法将其实施到Scheme中.我尝试使用map函数,但这似乎无法按照我想要的方式工作.有什么想法吗?

I am having trouble implementing this into Scheme. I tried using the map function but this doesn't seem to work the way I want it to. Any ideas?

推荐答案

我们首先定义两个输入列表,由于list是Scheme中的内置过程,因此不宜对其进行覆盖,因此我将其重命名. ):

We start by defining the two input lists, I renamed them since list is a built-in procedure in Scheme and is not a good idea to overwrite it):

(define l '(1 2 3 4))
(define l1 '(2 4 6 8))

我假设您希望结果列表是平坦的"-例如,它不包含元素列表,仅包含元素(如果您可以在l2中包含列表列表,只需删除将以下内容展平的调用).为此,我们需要定义flatten过程:

I'm assuming that you want your result list to be "flat" - e.g., it doesn't contain lists of elements, only elements (if you're ok with having a list of lists in l2, simply delete the call to flatten below). For that, we need to define the flatten procedure:

(define (atom? x)
  (and (not (pair? x)) (not (null? x))))

(define (flatten lst)
  (cond ((null? lst) empty)
        ((atom? lst) (list lst))
        (else (append (flatten (car lst))
                      (flatten (cdr lst))))))

最后,眼前的问题.一旦您了解了如何嵌套两个map过程,就很简单-看一下 SICP .

Finally, the problem at hand. It's simple once you understand how to nest two map procedures - take a look at the nested mappings section in the book SICP.

(define l2
  (flatten
   (map (lambda (i)
          (map (lambda (j)
                 (* i j))
               l1))
        l)))

此时,l2包含预期的答案:

At this point, l2 contains the expected answer:

(2 4 6 8 4 8 12 16 6 12 18 24 8 16 24 32)

这篇关于在Scheme编程中将列表的每个元素与另一个列表的每个元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆