如何在列表为空时停止prolog程序继续

时间:2017-10-28 02:22:33

标签: prolog

所以我正在学习prolog的基本编程,但我遇到了一些问题。我在prolog中使用append来从列表中删除前X个元素(X是我输入的任何随机数)。虽然当列表为空并且我要求列表中包含的内容超过时,程序会遇到问题。它应该返回[]。  输入。可拆卸(R,[1,2,3,A],5)

removable(A,B,N) :- length(X,N), append(X, A, B).

2 个答案:

答案 0 :(得分:1)

尽量避免像这样使用lengthappend。它使你的代码在列表中迭代很多。

相反,试试这个:

removable(0,R,R).
removable(X,[],[]) :- X > 0.
removable(X,[H|T],R) :- X > 0, Y is X - 1, removable(Y,T,R).

请注意我已经改变了你的参数的顺序,以遵循输入在左边和输出在右边的约定。

您的电话将是:

?- removable(5,[1,2,3,a],R), write(R).

输出[]

答案 1 :(得分:-1)

在prolog中,最好使用递归并尝试使用列表的头部和尾部。您已经实例化了所有三个vaiables,因此prolog无法实例化例如e的术语。

    removable(A,B,N) :-
  removable(A,B,N,0). % This is just another call with accumulator.



 removable(L,L,Acc,Acc). %This is your base case, When Acc and Acc will equal then prolog will find one succesive branch.

removable([],[],_,_). %This base case says that no matter what values Accs have if a list is emepty then substitue other also with empty list and return result.

 removable(R,[H|T],N,Acc) :-  %This predicates removes H and keeps counting when removed elements equal to N then first(base case) will succeed.
     NewAcc is Acc + 1,
     removable(R,T,N,NewAcc).

相关问题