0

this is simple yet cannot seem to grasp it I have these "colors"

color(blue).
color(red).
color(white).

using setof I need to get all possible combinations of these colors in a list It would be great if you can provide a brief explanation. I tried this query

setof(X,color(X),Colors). which failed obviously

Thanks

lurker
  • 56,987
  • 9
  • 69
  • 103
user3241846
  • 643
  • 3
  • 9
  • 26

2 Answers2

2

I suppose you meant this with combinations:

?- setof((X,Y), (color(X), color(Y)), ColorsCombined).
ColorsCombined = [ (blue, blue), (blue, green), (blue, red), (green, blue), (green, green), (green, red), (red, blue), (red, green), (..., ...)].

Or did you mean the superset?

subset([Element|Set], [Element|Subset]):- subset(Set, Subset).
subset([_|Set], Subset):- subset(Set, Subset).
subset([], []).

superset(Set, Superset) :- setof(Subset, subset(Set, Subset), Superset).

This is the output:

 ?- superset([1,2,3], Superset).
Superset = [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]].
User
  • 14,131
  • 2
  • 40
  • 59
  • Thanks, its basically what I wanted!! Just for further understanding I used this query `setof((X,Y,Z), (color(X), color(Y),color(Z)), ColorsCombined)`. and got three item tupples but I wanted to have a list of lists. e.g ColorsCombined = [(red,red,red),...] and what I wanted is ColorsCombined [[red,red,red],....] What do I need to change? – user3241846 Feb 13 '14 at 23:05
  • change the brackets from () to [] – User Feb 14 '14 at 07:33
2

You mean like this ?

all_permutations(Permutations) :-

    % get all colors into a list
    setof(Color, color(Color), One_Color_List),

    % find all combinations using permutation/2 on One_Color_List
    setof(Permutation, 
       permutation(One_Color_List, Permutation), 
       Permutations).

Results:

?- all_permutations(X).
X = [[blue, red, white], [blue, white, red], [red, blue, white], [red, white, blue], [white, blue, red], [white, red, blue]].

The trick is to get the facts into a list - as you did, then use permutation/2 to generate all permutations of that list.

If that's what you wanted.. wasn't clear...

magus
  • 1,347
  • 7
  • 13