3

I have the below implementation for the sublist algorithm. Problem: Given 2 lists, determine whether one is a sublist of the other. I would really need another distinct solution in Prolog.

Solution one:

sublist([H1|T1], L, [H2|T2]):-
  H1 = H2,
  sublist(T1, L, T2).
sublist([], _, _)
sublist([H1|T1],L,[H2|T2]):-
  sublist(L,L,T2).

Solution two:

sublist([H|T], [H|L]):- check(T,L),
sublist(S, [H|T]):- sublist(S,T).
check([H|T], [H|R]):-
   check(T,R).
check([],_).

Solution three:

sublist(S,L):-
  append(_,R,L),
  append(S,_,R).

Solution three':

sublist(S,L):-
  append3(_,S,_,L).
4

2 回答 2

2
?- phrase((...,seq(Sublist),...),List).

和:

... --> [] | [_], ... .

seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).

(警告:为了能够解释此解决方案,您需要先了解 DCG!)

于 2011-11-25T15:15:04.053 回答
0
sublist([], _).
sublist([H|T], List) :-
    select(H, List, R),!,
    sublist(T, R).

如果列表是按顺序排列的,则可以提高效率。

根据您的 Prolog 方言,select/3可能有不同的名称。

警告:根据 false 的评论,这更像是“子集”而不是“子列表”。

于 2011-11-25T15:24:39.957 回答