简体   繁体   English

列表列表-递归对序言

[英]list of lists- recursive pairs prolog

how can I put all the pairs in a one list? 如何将所有对放在一个列表中?

I have - 我有 -

pair([H|T], [H,E]) :- member(E, T).
pair([_|T], P) :- pair(T, P).

and I want the answer will be a list of pairs. 我希望答案将是成对的列表。

so I try - 所以我尝试-

listPairs([],[Res1]):-
      Res1=[].
listPairs(L,[Res2]):-
    L=[H|T],
    append(pair([H|T],[Res2]),listPairs(T,[Res2])).

but I miss something of the lists.. because it is not compile. 但我错过了一些清单..因为它没有被编译。

I don't really see what you aim to do with append/2 . 我真的看不到您打算对append/2做些什么。 You can definitely not put goals that should be called in the append/3 because in that case, they will be seen as functors. 您绝对不能将目标应该在append/3调用,因为在这种情况下,它们将被视为函子。

You can however easily use the findall/3 predicate which is implemented in nearly all Prolog systems (well at least all I have seen that are actively used): 但是,您可以轻松地使用几乎在所有Prolog系统中实现的findall/3谓词(至少我所看到的所有正在使用的谓词):

listPairs(L,Pairs) :-
    findall(Pair,pair(L,Pair),Pairs).

findall/3 works as follows: findall/3工作方式如下:

findall(Format,Goal,List).

Here you specify a Goal (here pair(L,Pair) ) and Prolog will call the Goal . 在这里,您可以指定一个Goal (此处为pair(L,Pair) ),Prolog会将其称为Goal Each time the Goal succeed, Prolog will suspend the interpreter and add en element formatted as Format to the List . 每次Goal成功,Prolog的将暂停解释,并添加带格式化为元素FormatList When the Goal fails, the list of all Format s is returned. Goal失败时,将返回所有Format的列表。

If I run the query, I get: 如果运行查询,则会得到:

?- listPairs([1,a,2,'5'],Pairs).
Pairs = [[1, a], [1, 2], [1, '5'], [a, 2], [a, '5'], [2, '5']].

Note that L must be grounded (as list, meaning without uninstantiated tail, an uninstantiated element is fine), since otherwise the number of pair/2 elements that you will generate is infinite and thus you will run out of global stack (or memory in general). 请注意, L必须接地(如列表所示,意味着没有未实例化的尾巴,一个未实例化的元素就可以了),因为否则,您将生成的pair/2元素的数量是无限的,因此您将耗尽全局堆栈(或内存在一般)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM