浏览清单Prolog [英] Going through lists Prolog

查看:60
本文介绍了浏览清单Prolog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在Prolog中工作,但在理解如何解决问题方面遇到困难.我正在尝试做的是创建3个元素的元组,每个元素都来自不同的列表.我需要做的是,从三个列表中为每种可能的组合制作一个三元组.我的计划是获取两个列表中的第一个元素,然后遍历第三个列表中的每个元素,为每个元素创建一个元组.然后将第一个列表中的第一个元素和第二个列表中的第二个元素放在一起,并再次遍历第三个列表中的每个元素.我了解这可能很难遵循.我的总体目标是为三个列表中的每种可能组合创建一堆元组.元组中的第一个元素来自第一个列表,第二个元素来自第二个列表,第三个元素来自第三个列表.

I'm trying to work in Prolog and I'm having trouble understanding how to solve my problem. What I am trying to do is create tuples of 3 elements each one from a different list. What I need to do is make a tuple of three for every possible combination out of three lists. My plan is to take the first element in two of the lists and then go thru every element in the third list creating a tuple for each. Then take the first element in the first list and the second element in the second list and go thru each element in the third list again. I understand this may be hard to follow. My overall goal is to create a bunch of tuples for each possible combinations from the three lists. The first element in the tuple is from the first list, the second element is from the second list, and the third element is from the third list.

我是Prolog的初学者,因此我对应该走的方向以及如何用代码写出自己的想法感到困惑.因此,任何帮助将不胜感激.

I'm a beginner in prolog so I'm a little confused on what direction I need to go and how to write my thoughts in code. So any help would be greatly appreciated.

谢谢

推荐答案

您能为两个列表解决此问题吗?如果是这样,那么您 就能解决其中的任意个问题:

Are you able to solve this for two lists? If so, then you are able to solve it for any number of them:

pairup_lists( [A, B | T] ,    X ):-
   pairup_lists( [B | T] , Y),
   pairup_two_lists( A,    Y, X).

您将需要在此处添加一些特殊情况,并实现 pairup_two_lists/3 谓词.

You will need to add some corner case(s) here, and implement the pairup_two_lists/3 predicate.

预先知道只有三个,可以内联递归并将所有内容融合为一个谓词 pairup_three_lists/4 .

Knowing in advance there will be only three of them, you can inline the recursion and fuse everything into one predicate, pairup_three_lists/4.

那么,如何解决 pairup_two_lists/3 问题?

如果第一个列表是单例列表,那么问题是否就等同于另一个更简单的 pair_up_an_element_and_a_list/3 问题?

If the first list is a singleton list, doesn't the problem then become equivalent to another, simpler, pair_up_an_element_and_a_list/3 problem?

如果第一个列表中包含更多元素,那么可以将其分为头和尾,那么在没有更多元素的情况下,逐个元素地处理尾列表不是相同的逻辑处理?

And if the first list has more elements in it, so it can be split into a head and a tail, doesn't that same logic apply to dealing with the tail list, element by element, until there are no more elements to deal with?

这篇关于浏览清单Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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