【问题标题】:Retracting and asserting to another file in Prolog在 Prolog 中撤回并断言到另一个文件
【发布时间】:2014-12-21 18:31:38
【问题描述】:

我正在尝试在另一个文件中撤回和断言一个事实。一个 (fruit1.pl) 包含几个事实,另一个 (fruit.pl) 包含一个谓词 start,它指定另一个谓词 insert_fruit 将更新哪个事实:

fruit1.pl

fruit(apple, [[2, yellow], [1, brown]]).
fruit(orange, [[3, orange], [2, orange]]).

fruit.pl

:- dynamic fruit/2.

start :-
    consult('fruit1.pl'),
    File = 'fruit1.pl',
    Name = apple,
    Price = 2,
    Color = red,
    insert_fruit(File, Name, Price, Color). 

insert_fruit(File, Name, Price, Color) :-
   open(File, update, Stream),
   retract(fruit(Name, Information)),
   assert(fruit(Name, [[Price, Color]|Information])),
   close(Stream). 

但是insert_fruit 没有按预期工作,因为我认为它需要包含 Stream 才能修改其他文件,尽管我不知道如何(retract(Stream, ...) 不起作用)。是否有一些我可以让撤回和断言谓词在另一个文件中起作用?

【问题讨论】:

  • 你正在尝试的东西不会像这样工作。 assertretract 操作谓词“数据库”,而不是当前打开的文件。您之前曾问过类似的问题,并得到了评论和答案;阅读它们。
  • 你见过this question吗?我在那里给出了答案。还有,鲍里斯说的。

标签: prolog prolog-directive-dynamic


【解决方案1】:

在 SWI-Prolog 中,您可以使用 library persistency 从用作持久事实存储的文件中断言/收回事实:

  1. 您将fruit/3 声明为持久性。可选:使用类型注释参数以进行自动类型检查。
  2. 您附加一个文件,该文件将在 fruit 模块(在本例中为 fruit1.pl)初始化时用作持久事实存储。
  3. 您添加了用于插入(即add_fruit/3)和查询(即current_fruit/3)果味事实的谓词。撤回的处理方式类似。
  4. 请注意,您可以通过 with_mutex/2 在多线程环境中使用事实存储(当您开始收回事实时尤其有用)。

代码

:- module(
  fruit,
  [
    add_fruit/3, % +Name:atom, +Price:float, +Color:atom
    current_fruit/3 % ?Name:atom, ?Price:float, ?Color:atom
  ]
).

:- use_module(library(persistency)).

:- persistent(fruit(name:atom, price:float, color:atom)).

:- initialization(db_attach('fruit1.pl', [])).

add_fruit(Name, Price, Color):-
  with_mutex(fruit_db, assert_fruit(Name, Price, Color)).

current_fruit(Name, Price, Color):-
  with_mutex(fruit_db, fruit(Name, Price, Color)).

使用说明

启动Prolog,加载fruit.pl,执行:

?- add_fruit(apple, 1.10, red).

关闭 Prolog,再次启动 Prolog,执行:

?- current_fruit(X, Y, Z).
X = apple,
Y = 1.1,
Z = red

您现在正在阅读来自fruit1.pl 的事实!

自动类型检查说明

如前所述,该库还为您执行类型检查,例如:

?- add_fruit(pear, expensive, green).
ERROR: Type error: `float' expected, found `expensive' (an atom)

【讨论】:

  • 嗨,Wouter,很好的答案。不知道是否支持QLF?
  • @CapelliC 你的意思是准逻辑形式吗?我对此并不熟悉,也不知道它在这里如何应用......你能举一个QLF w.r.t的例子吗?持久存储?
  • 不,更低级别...Quick Load Format
  • 感谢您非常有见地的回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
相关资源
最近更新 更多