prolog中列表的常见子序列

时间:2017-06-24 15:12:52

标签: prolog

我试图写一个谓词common(L,S),它从列表L列表中生成L中列表中所有公共子序列。

subseq([], _).
subseq([H|S], L) :- append(_, [H|T], L), subseq(S, T).


common(L, X) :- not((
        member(A, L),
        not(subseq(X, A))
       )).

它只是给了我真实的'即使输入错误。

例如:

common([[1,2,3,4], [2,3], [12]], X). true

修改

我注意到它实际上正在工作,但它并没有用谓词为真的术语代替X.

1 个答案:

答案 0 :(得分:9)

子字符串是后缀的非空前缀。

substring_of(Ys, Xs) :-
   Ys = [_|_],           %  a non-empty
   append(_, Zs, Xs),    %                       a suffix of Xs
   append(Ys, _, Zs).    %             prefix of 

common(Xss, Xs) :-       % Xs is a substring of each element of Xss
   maplist(substring_of(Xs), Xss).

?- common([[1,2,3,4], [2,3,4,5]], Xs).
Xs = [2] ;
Xs = [2, 3] ;
Xs = [2, 3, 4] ;
Xs = [3] ;
Xs = [3, 4] ;
Xs = [4] ;
false.