Subsets in Prolog

后端 未结 5 721
栀梦
栀梦 2020-11-29 10:14

I\'m looking for a predicate that works as this:

?- subset([1,2,3], X).
X = [] ;
X = [1] ;
X = [2] ;
X = [3] ;
X = [1, 2] ;
X = [1, 2, 3] ;
X = [2, 3] ;
...
         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 10:53

    we can also test by deleting subset's item from the super set.

    % to delete : an item can be deleted it its in the head or in the tail of a list
    delete(I,[I|L],L).
    delete(I,[H|L],[H|NL]) :- delete(I,L,NL).
    % an [] is an item of an set.A set is a subset of we can recursively delete its head item from the super set.
    subset(_,[]).
    subset(S,[I|SS]) :- delete(I,S,S1), subset(S1,SS).
    

    example:

    subset([a,b,c],S).
    S = []
    S = [a]
    S = [a, b]
    S = [a, b, c]
    S = [a, c]
    S = [a, c, b]
    S = [b]
    S = [b, a]
    S = [b, a, c]
    S = [b, c]
    S = [b, c, a]
    S = [c]
    S = [c, a]
    S = [c, a, b]
    S = [c, b]
    S = [c, b, a] 
    

    subset([a,b,a,d,e],[a,e]).
    1true
    

提交回复
热议问题