如何重写orolog谓词,以便列出所有可能的答案

时间:2016-11-24 18:03:34

标签: prolog

当列表C包含列表A中不属于列表B的元素时,谓词diff(A, B, C)应为true。

in_list([], []).    
in_list(S, [S | _]).
in_list(S, [H | T]) :-
    S \= H,
    in_list(S, T).


diff([H], T, [H]) :- not(in_list(H, T)), !.
diff([H | T1], T, [H]) :-
    not(in_list(H, T)),
    not(diff(T1, T, _)), !.
diff([H | T1], T, [Hr]) :-
    diff(T1, T, [Hr]),
    H \= Hr,
    in_list(H, T), !.

diff([H1 | T2], S2, [H1 | Tr]) :-
    not(in_list(H1, S2)),
    diff(T2, S2, Tr).

diff([H1 | T2], S2, [Hr | Tr]) :-
    in_list(H1, S2),
    diff(T2, S2, [Hr | Tr]).

diff([H1 | T2], S2, [Hr | Tr]) :-
    in_list(Hr, T2),
    Hr \= H1,
    not(in_list(Hr, S2)),
    diff([H1 | T2], [Hr | S2], Tr).

我的问题是它检查正确,例如: ?- diff([1, 2, 3, 4], [2], [3, 4, 1]).是真的, 但当被要求输出所有可能的答案时,我只得到:

?- diff([1, 2, 3, 4], [2], R).
R = [1, 3, 4] ;
R = [1, 4, 3] ;
R = [1, 3, 4] ;
false.

修改:预期输出 - 所有变体

?- diff([1, 2, 3, 4], [2], R).
R = [1, 3, 4] ;
R = [1, 4, 3] ;
R = [3, 1, 4] ;
R = [3, 4, 1] ;
R = [4, 1, 3] ;
R = [4, 3, 1] ;
false.

或类似的东西。

2 个答案:

答案 0 :(得分:1)

以下是我要做的事情:

my-member([X|_], X).
my-member([_|T], X) :- my-member(T, X).

my-append([], L, L).
my-append([H|T], L, [H|R]) :- my-append(T, L, R).

my-prune([], []).
my-prune([H|T], R) :-
    my-prune(T, R1),
    (
        (my-member(R1, H), my-append([], R1, R));
        (not((my-member(R1, H))), my-append([H], R1, R))
    ), !.

my-complementation-uniques(_, [], []).
my-complementation-uniques([], _, []).
my-complementation-uniques([H|T], R, U) :-
    my-complementation-uniques(T, R, U1),
    (
        (
            my-member(R, H),
            my-append([], U1, U)
        );
        (
            not((my-member(R, H))),
            (
                (
                    my-member(U1, H),
                    my-append([], U1, U)
                );
                (
                    not((my-member(U1, H))),
                    my-append([H], U1, U)
                )
            )
        )
    ), !.

my-complementation(L, R, U) :-
    my-prune(L, L1),
    my-prune(R, R1),
    my-complementation-uniques(L1, R1, U).

insert(X, A, Y) :- my-append(L, M, X),

答案 1 :(得分:0)

这是我的实施:

my_diff(L1,L2,R):-not_members(L1,L2,List),combinations(List,R).

not_members([],_,[]).
not_members([H|T],L,R):-member(H,L),not_members(T,L,R).
not_members([H|T],L,[H|R]):- \+member(H,L),not_members(T,L,R).

combinations([],[]).
combinations(L,[X|Xs]) :- choice(X,L,R), combinations(R,Xs).

choice(X,[X|L],L).
choice(X,[H|L],[H|R]) :- choice(X,L,R).

示例:

?- my_diff([1, 2, 3, 4], [2], R).
R = [1, 3, 4] ;
R = [1, 4, 3] ;
R = [3, 1, 4] ;
R = [3, 4, 1] ;
R = [4, 1, 3] ;
R = [4, 3, 1] ;
false.