问题描述
有人可以帮我找到这些规则中的错误吗?
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
推荐答案
要修改代码,按预期的方式,您只需在上次调用中将Head
转换为[Head]
即可,最后一句.问题是您仅使用Head
作为第一个参数(而不是列表)来调用谓词.
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.
不过,这里有几个注意事项:
Though, here are several notes :
-
[Head|[]]
等同于[Head]
- 您的算法的复杂度很差,n!我相信.
- 在第二个子句之后未插入剪切,您可以通过调用长度为1的列表的第三个子句来生成无限选择点(因此调用了第二个子句,然后再遍历第三个子句,依此类推. .无限循环).
[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).
这是SWI-pl的版本,以提示您迈向良好的序言递归:
Here is SWI-pl's version, to hint you towards good prolog recursion :
append([], List, List).
append([Head|Tail], List, [Head|Rest]) :-
append(Tail, List, Rest).
您可以在这里或在立即学习Prolog中找到其他资源!
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.
这篇关于Prolog中列表的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!