Prolog谓词,在给定的单词列表中紧跟一个单词后提取所有单词

时间:2017-05-11 15:55:55

标签: prolog

正如标题中所说,我需要在prolog中的特定单词之后得到所有单词,例如:

?- find([in, house, car, in, shop, no, more, apples, in, table], in , X).

X = [house, shop, table] ;

No

这是我到目前为止编写的代码:

find([H,H_1|_],H,[H_1]).
find([Head,Head_1|Tail], Term, [Head|Result]) :-
     find(Tail, Term, Result).

运行后,我得到:

X = [house] ;

X = [in, car, shop, more, table] ;

No

1 个答案:

答案 0 :(得分:0)

主要问题可能在于:

find([H,H_1|_],H,[H_1]).

此代码在匹配后将列表与第一个元素统一起来。然后,您将第三个参数(此处用作"结果")与包含单个事件的列表统一起来。

另外请注意,我们也可能到达列表的末尾。因此,在这种情况下,谓词也会失败。

基本上有四种情况:

  • 我们到达列表的末尾,"结果"参数应与空列表统一;
  • 我们找到了元素并且有一个下一个元素(也是匹配),我们执行一步并继续搜索;
  • 我们找到了元素并且有一个下一个元素(匹配),我们添加该元素并继续我们的搜索;
  • 头部不匹配,我们继续搜索。

我们可以将这些可能性实现为:

find([],_,[]).            % we reach the end of the list


find([H,H|T],H,T2) :-     % there is a match, the successor is also a match
    find([H|T],H,T2).     % perform one hop

find([H,N|T],H,[N|T2]) :- % there is a match, add the next element
    N \= H,
    find(T,H,T2).         % and continue

find([N|T],H,T2) :-       % there is no match
    N \= H,
    find(T,H,T2).         % we continue

这会产生:

?- find([in, house, car, in, shop, no, more, apples, in, table], in , X).
X = [house, shop, table] ;
false.

?- find([a,b,c],c,X).
false.

?- find([a,b,c,a,d],a,X).
X = [b, d] ;
false.

?- find([a,a,b],a,X).
X = [b] ;
false.

Yes / No位于 true/false)。

相关问题