1

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

水果1.pl

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

水果.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, ...)不起作用)。是否有一些我可以让撤回和断言谓词在另一个文件中起作用?

4

1 回答 1

4

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

  1. 你声明fruit/3为持久的。可选:您使用类型注释参数以进行自动类型检查。
  2. 您附加一个文件,该文件将在模块初始化时用作持久事实存储fruit(在本例中fruit1.pl)。
  3. 您添加用于插入 (ie, add_fruit/3) 和查询 (ie, current_fruit/3) 果味事实的谓词。撤回的处理方式类似。
  4. 请注意,您可以通过 using 在多线程环境中使用事实存储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)
于 2014-10-27T01:19:30.743 回答