Search code examples
prologlogic

Not able get all subsets of a list in prolog using subset/2


This seems to be working fine:

?- subset([1, 3, 4], [1, 2, 3, 4, 5]).
true.
?- subset([1, 2], [1, 4, 2, 3]).
true.

But I'm not able to get all such possible subsets using the same format:

?- subset(X, [1, 2, 3, 4, 5]).
ERROR: No rule matches lists:subset(_3308,[1,2,3,4,5])
ERROR: In:
ERROR:   [10] lists:subset(_3390,[1,2|...])
ERROR:    [9] toplevel_call(user:user: ...) at c:/program files/swipl/boot/toplevel.pl:1158

I'm new to prolog, isn't this how you ask it to find you values? what am I missing here?


Solution

  • Try this definition:

    sub_set([], []).
    sub_set( S, [X|Xs]) :-
        sub_set(Ys, Xs),
        (   S = Ys
        ;   S = [X|Ys]  ).
    

    Example:

    ?- sub_set(S, [1,2,3]).
    S = [] ;
    S = [1] ;
    S = [2] ;
    S = [1, 2] ;
    S = [3] ;
    S = [1, 3] ;
    S = [2, 3] ;
    S = [1, 2, 3].