Search code examples
prologlogicprolog-setof

Simple Prolog setof


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


Solution

  • 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]].