質問

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

役に立ちましたか?

解決

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

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top