首页 > 解决方案 > 如果在列表中,Prolog如何在列表中添加元素

问题描述

我正在尝试用我自己的谓词做一个列表成员( member/2 )。

开始这个例子

?-app([a,r,t],[t,s,m,n,a],L3). 

L3=[a,t]

我试着做类似的练习,所以我用 prolog 做了这个:

app([],_,[]).
app([H|T],[H1,T1],[H|L1]):- H is H1,  L1 is H,! ,app(T,T1,L1).
app([_H|T],L,L2):-  app(T,L,L2).

并且所有工作正常,但是列表中的值将在执行过程中被覆盖,实际上,跟踪是:

trace, app([3,2],[3,5],X).
   Call: (9) app([3, 2], [3, 5], _7426) ? creep
   Call: (10) 3 is 3 ? creep
   Exit: (10) 3 is 3 ? creep
   Call: (10) _7736 is 3 ? creep
   Exit: (10) 3 is 3 ? creep
   Call: (10) app([2], 5, 3) ? creep
   Call: (11) app([], 5, 3) ? creep
   Fail: (11) app([], 5, 3) ? creep
   Fail: (10) app([2], 5, 3) ? creep
   Fail: (9) app([3, 2], [3, 5], _7426) ? creep
false.

我试图以这种方式对基本情况进行修改:

app([],_,_N).

但输出完全错误:

trace, app([3,2],[3,5],X).
   Call: (9) app([3, 2], [3, 5], _7426) ? creep
   Call: (10) 3 is 3 ? creep
   Exit: (10) 3 is 3 ? creep
   Call: (10) _7736 is 3 ? creep
   Exit: (10) 3 is 3 ? creep
   Call: (10) app([2], 5, 3) ? creep
   Call: (11) app([], 5, 3) ? creep
   Exit: (11) app([], 5, 3) ? creep
   Exit: (10) app([2], 5, 3) ? creep
   Exit: (9) app([3, 2], [3, 5], [3|3]) ? creep
X = [3|3].

我错在哪里?

标签: prolog

解决方案


我认为你正在尝试做一个sublist/2谓词:

%! sublist(Sub, List)
% is true if Sub is a list that occurs in
% some position in List
sublist(Sub, List) :-
    % first partition off some tail of the list
    append(_Prefix, Tail, List),
    % then get some prefix of the tail, this is a sublist
    append(Sub, _TailTail, Tail).

有更多的方法可以做到这一点,但我认为append/3很容易理解。这是一个与在列表中查找元素不同的问题member/2,这里我们的问题是将列表分成块,因此实现与您在 中看到的非常不同member/2。在 Prolog 中,您经常会发现解决方案的第一步是很好地定义问题。祝你在 Prolog 学习中好运。


推荐阅读