【问题标题】:how can I print all database facts in prolog如何在序言中打印所有数据库事实
【发布时间】:2011-12-15 04:05:19
【问题描述】:

我在 prolog 中有一个数据库,我想做的就是枚举它的元素并一一打印。如何做到这一点?

fact(is(mike,asthmatic)).
fact(has(andy,highPressure)).
fact(is(mike,smoker)).

我已经写了这个,它工作正常,但是它从数据库中删除了元素,所以我想访问它们而不删除。

print:- 
  retract(factA(P)),
    write(factA(P)),nl,
    fail.
  print.

【问题讨论】:

标签: prolog


【解决方案1】:

您也可以考虑使用forall/2 谓词:

print:-
 forall(fact(P), writeln(P)).

【讨论】:

  • 当我将此代码更改为:print:-forall(fact(P), (write(P), nl)) 时它起作用了。你能告诉我为什么 writeln 不起作用吗?它依赖于编译器吗?
  • 这取决于谓词writeln/1 是否可用于您的实现。好像不是!你用的是哪个序言?
  • 显然 GNU Prolog 没有 writeln(Term),正如您所说,它等同于 (write(Term), nl)。因此,您也可以编写自己的 writeln/1 版本:writeln(Term):- write(Term), nl.
【解决方案2】:

嗯,你快到了:

print :-
    fact(A),
    writeln(A),

首先,我们得到一个事实并打印出来。

    fail;true.

然后,我们回溯(通过失败),直到没有解决方案。为了避免返回 false,我们添加了与 true 的析取。

请注意,您可以采取不同的方式,例如:

print2 :-
    findall(Fact, fact(Fact), Facts),
    maplist(writeln, Facts).

但如果你走这条路,更喜欢@gusbro 解决方案,那就更好了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2012-01-07
    相关资源
    最近更新 更多