【问题标题】:Simple Prolog setof简单的 Prolog 集
【发布时间】:2014-02-13 20:15:05
【问题描述】:

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

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

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

setof(X,color(X),Colors). 显然失败了

谢谢

【问题讨论】:

    标签: prolog logic prolog-setof


    【解决方案1】:

    我想你的意思是组合:

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

    【讨论】:

    • 谢谢,这基本上是我想要的!只是为了进一步理解,我使用了这个查询setof((X,Y,Z), (color(X), color(Y),color(Z)), ColorsCombined)。并得到三个项目元组,但我想要一个列表列表。例如 ColorsCombined = [(red,red,red),...] 而我想要的是 ColorsCombined [[red,red,red],....] 我需要改变什么?
    • 将括号从 () 更改为 []
    【解决方案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]].
    

    诀窍是将事实放入一个列表 - 就像您所做的那样,然后使用 permutation/2 生成该列表的所有排列。

    如果那是你想要的……不清楚……

    【讨论】:

    • 确实是我想要的,谢谢!!
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多