简单的Prolog setof

时间:2014-02-13 20:15:06

标签: prolog logic prolog-setof

这很简单但似乎无法掌握它 我有这些“颜色”

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

使用setof我需要在列表中获得这些颜色的所有可能组合 如果你能提供一个简短的解释,那就太好了。我试过这个查询

明显失败的

setof(X,color(X),Colors).

由于

2 个答案:

答案 0 :(得分:2)

我想你的意思是组合:

?- 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), (..., ...)].

或者你的意思是超集?

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

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

这是输出:

 ?- superset([1,2,3], Superset).
Superset = [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]].

答案 1 :(得分:2)

你的意思是这样吗?

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

结果:

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

诀窍是将事实放入列表中 - 就像你一样,然后使用置换/ 2来生成该列表的所有排列。

如果这就是你想要的......还不清楚...

相关问题