【问题标题】:How to remove duplicate facts in Prolog如何在 Prolog 中删除重复的事实
【发布时间】:2013-10-10 13:09:55
【问题描述】:

我正在 Prolog 中编写一个规则来创建一个事实,pit(x,y)。下面的这条规则在我的 main 函数中被调用了 3 次,它插入了三个坑,其中没有一个在 (1,1) 或 (1,2) 或 (2,1) 但问题是有时 2 个坑具有相同的 x 和 y,其中 x 和 y 只能从 1 到 4。 (4x4 网格)

placePit(_) :-   Px is random(4)+1,
                 Py is random(4)+1,
                 write(Px),
                 write(' '),
                 writeln(Py),
                 (Px =\= 1; 
                 Py =\= 1),
                 (Px =\= 1;
                 Py =\= 2),
                 (Px =\= 2;
                 Py =\= 1)
                 ->
                 pit(Px,Py);
                 placePit(4).

我不希望这种情况发生,所以我写了另一个规则来检查 2 个坑是否相同,然后将扩展为从数据库中删除任何一个。根据我的测试,即使 2 个坑看起来相同,它也不会被解雇。我究竟做错了什么?如何去除重复的事实?

pit(A,B) :- pit(C,D), 
            A = C, 
            B = D, 
            write('Duplicate').

PS。我是 Prolog 的新手。任何建议表示赞赏。

【问题讨论】:

    标签: prolog duplicates fact


    【解决方案1】:

    也许这会有所帮助,假设您实际上需要生成事实

    :- dynamic(pit/2).
    
    pit(1,1).
    pit(1,2).
    pit(2,1).
    
    placePit(N) :-
      N > 0,
      Px is random(4)+1,
      Py is random(4)+1,
      ( \+ pit(Px, Py)         % if not exist
      -> assertz(pit(Px, Py)), % store
         M is N-1              % generate another
      ;  M = N                 % nothing changed, retry
      ),
      placePit(M).             % recursion is the proper Prolog way to do cycles
    placePit(0).               % end of recursion (we call it 'base case')
    

    你应该叫

    ?- placePit(3).
    

    它显示了一些句法细节,比如“if/then/else”,在 Prolog 中有一种特殊的形式。

    编辑完成后,您可以删除不需要的 pit/2,让您的数据库“干净”。

    ?- maplist(retract, [pit(1,1),pit(1,2),pit(2,1)]).
    

    (请注意,我假设 - 根据您的描述 - DB 存储的 pit/2 对进一步处理具有价值)。

    【讨论】:

    • 谢谢。它工作得很好,但是如何删除pit(1,1)、pit(1,2)和pit(2,1)。这三个我不要(可能我不够清楚)。
    • 查看我的编辑。也许基于列表的解决方案会更好,但是您的问题没有显示任何列表用法...然后我坚持使用数据库处理。
    猜你喜欢
    • 2011-01-16
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多