Prolog is a subset of

I'm a little new to Prolog. I am trying to write a subset of functions (Set, Subset) that determines if Subset is a subset of Set (spirit). In addition, if the second parameter is not created, it should output all possible subsets. Right now, this works when both parameters are created, but when I try to output all the subsets, it encounters a problem with member / 2. For instance:

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

Here is my code:

% subset/2
% subset(Set, Subset) iff Subset is a subset of Set
subset(_, []).
subset(Set, [H|T]) :-
  member(H, Set),
  subset(Set, T).

How to make sure that the participant does not choose the first option in the set?

+5
source share
4 answers

(Many Prolog systems, including SICStus and SWI, have subset/2in their library, but rather subset(Subset, Set), this is also not a pure relation ...)

, . [1, 1] ? ? , . :

set_subset(Set, Subset): Subset Set

, , . , , . , , :

?- length(Subset,N), set_subset([1,2,3], Subset).
Subset = [], N = 0 ;
Subset = [1], N = 1 ;
Subset = [2], N = 1 ;
Subset = [3], N = 1 ;
Subset = [1, 1], N = 2 ;
Subset = [1, 2], N = 2 ;
Subset = [1, 3], N = 2 ;
Subset = [2, 1], N = 2 ;
Subset = [2, 2], N = 2 ;
Subset = [2, 3], N = 2 ...

, Subset , , , . . .

+3

, , , . , :

% subset(-Set, +Set)
subset([X|L], [X|R]) :-
   subset(L, R).
subset(L, [_|R]) :-
   subset(L, R).
subset([], []).

:

:

?- subset(X, [1,2,3]), write(X), nl, fail; true.
[1,2,3]
[1,2]
[1,3]
[1]
[2,3]
[2]
[3]
[]

:

?- subset([1,2,3], X), write(X), nl, fail; true.
[]
[1]
[1,2]
[1,2,3]
[1,3]
[1,3,2]
[2]
[2,1]
[2,1,3]
[2,3]
[2,3,1]
[3]
[3,1]
[3,1,2]
[3,2]
[3,2,1]

| P (A) | = 2 ^ | A |, 3- 8 . , , .

+2

/2, /3

subset(_, []).
subset(Set, [H|T]) :-
  select(H, Set, Rest),
  subset(Rest, T).

?- subset([a,b,c],X).
X = [] ;
X = [a] ;
X = [a, b] ;
X = [a, b, c] ;
X = [a, c] ;
...
+1

guys. Can someone help me with the following task: I need to determine the eq_set predicate, which succeeds if the sets S1 and S2 are equal when it comes to the number of their elements. I wrote: eq_set ([], []). eq_set ([H | T], [H | T1]): -eq_set (T, T1). But this only works if they are exactly the same number and order. I want to create code that shows all varieties and does not take order into account. could you help me?

0
source

All Articles