【问题标题】:How to print all the facts?如何打印所有事实?
【发布时间】:2015-06-20 02:23:16
【问题描述】:

我被这个问题困住了......

isAt(keys, room3).
isAt(book, room3).
isAt(keys, room6).
isAt(keys, room4).

目前,room3 有钥匙和书。 我想打印钥匙和书。 我试过这段代码,显然只打印了一个。 (只是键)

look :- isIn(Location),
  write('You are in '),
  write(Location),
  nl,
  items_inroom(Location),
  nl.


items_inroom(Location) :-
    isIn(Location),
    isAt(Item, Location),
    write('Available Item(s):'), 
    write(Item),
    nl.

items_inroom(_) :-
    write('Available Item(s): None'),
    nl. 

items_inroom 是试图打印所有这些事实的代码。 我该如何处理? 任何帮助都会很棒!谢谢。

【问题讨论】:

    标签: list printing prolog fact


    【解决方案1】:

    来自 Richard O'Keefe 在"The Craft of Prolog" 中的第 11 章,稍微简化/重构以节省击键:

    print_item_report(位置):- ( setof(Item, isAt(Item, Location), Items) -> format("~w:~n 中可用的项目", [Location]), forall(成员(我,项目), 格式(“~w~n”,[I])) % print_item_report_footer ; format("~w~n 中没有项目", [Location]) )。 % ETC

    如果您由于某种原因没有format,您仍然可以使用write。如果你没有forall,那么这个:

    forall(Condition, Action)
    

    定义为

    \+ (Condition, \+ Action )
    

    所以你可以使用它。详情请见the SWI-Prolog forall/2 documentation

    【讨论】:

      【解决方案2】:

      找到所有项目并显示它们。

      items_inroom(Location) :-
          write('Available Item(s):'),
          findall(Item, isAt(Item, Location), Items),
          show_items(Items).
      
      show_items([]) :-
          write('None'), !.
      
      show_items(Items) :- 
          write(Items).
      

      实际上你可以用任何你想要的方式实现show_items(Items)

      【讨论】:

      • 理想情况下,您应该使用bagof/3setof/3 而不是findall(因为如果没有解决方案它们会失败,并且不要践踏选择指向@987654326 的方式@ 确实)。
      • @Boris 你是对的。我的主要目的是明确区分数据处理用户界面
      【解决方案3】:

      items_inroom/1 谓词将始终在所有事实isAt/2 上打印Item 的第一次出现。您需要遍历所有事实isAt/2,使用元谓词setof/3bagog/3findall/3,我会像@Boris 那样推荐setof/3,或者构建自己的bucle(也许不是最好的主意,但这是一种选择):

      show_items(Location):- isAt(Item, Location),   % Condition
                           write(Item), nl,          % Process result
                           fail.                     % force backtracking to evaluate condition and find a new result
      show_items(_).                                 % return true when all options have been evaluated
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        • 2021-12-13
        • 2015-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多