list Prolog中列表的串联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9348640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenation of Lists in Prolog
提问by damluar
Can someone help me find the error in these rules?
有人可以帮我找出这些规则中的错误吗?
concat([], List, List).
concat([Head|[]], List, [Head|List]).
concat([Head|Tail], List, Concat) :- concat(Tail, List, C), concat(Head, C, Concat).
Trying to concatenate two lists fails:
尝试连接两个列表失败:
| ?- concat([1,2], [4,7,0], What).
no
回答by m09
To fix your code, the way you intended it, you just need to transform Head
into [Head]
in your last call to concat/3
in your last clause. The problem was that you called your predicate with Head
only as first argument, which is not a list.
要修复您的代码,按照您的预期方式,您只需要在最后一个子句中的最后一次调用中转换Head
为。问题是你只用第一个参数来调用你的谓词,这不是一个列表。[Head]
concat/3
Head
Though, here are several notes :
不过,这里有几个注意事项:
[Head|[]]
is equivalent to[Head]
- your algorithm has a poor complexity, n! I believe.
- with no cut inserted after your second clause, you generate infinite choice points through the call of your third clause with a list of length 1 (that hence calls your second clause, that then is ran through your third clause, etc... infinite loop).
[Head|[]]
相当于[Head]
- 你的算法复杂度很低,n!我相信。
- 在您的第二个子句之后没有插入剪切,您通过调用您的第三个子句和长度为 1 的列表生成无限选择点(因此调用您的第二个子句,然后通过您的第三个子句运行,等等......无限循环)。
Here is SWI-pl's version, to hint you towards good prolog recursion :
这是 SWI-pl 的版本,向您提示良好的序言递归:
append([], List, List).
append([Head|Tail], List, [Head|Rest]) :-
append(Tail, List, Rest).
You can find other resources on recent posts here or in Learn Prolog Now!tutorial if you want to learn how to use recursion properly.
您可以在此处或立即在Learn Prolog 中找到有关最近帖子的其他资源!如果你想学习如何正确使用递归,教程。
回答by Jo?o Rodrigues
It can be done by using append.
它可以通过使用 append 来完成。
concatenate(List1, List2, Result):-
append(List1, List2, Result).
Hope this helps.
希望这可以帮助。
回答by Ratan Deb
Here is the concatenation between two lists rule:
这是两个列表规则之间的连接:
concat([],L2,L2). concat([Head|Tail],L2,[Head|L3]) :- concat(Tail,L2,L3).
回答by Ch3steR
The implementation is very simple. concatenation is nothing but appending the second list at the end of the first list. Keep on adding until the first list runs out of elements. Now add the second list to it.
实现非常简单。连接只不过是在第一个列表的末尾附加第二个列表。继续添加,直到第一个列表用完元素。现在将第二个列表添加到其中。
ap([],L,L).
ap([H|T],L,[H|Z]):- ap(T,L,Z).
OUTPUT
输出
?-ap([1,2,3],[a,b,c],List).
List=[1,2,3,a,b,c]
?-ap([1,2,3],[a,b],List).
List=[1,2,3,a,b]
?-ap([1,2],[a,b,c],List).
List([1,2,a,b,c])
?-ap([],[],List).
List=[]