Issues with storage of facts in Prolog

断了今生、忘了曾经 提交于 2019-12-02 06:01:49

Saving state has certain limitations, also see the recent discussion on the SWI-Prolog mailing list.

I think the easiest way to persistently store facts on SWI-Prolog is to use the persistency library. For that I would rewrite your code in the following way:

:- use_module(library(persistency)).

:- persistent fact(fact1:any, fact2:any).

:- initialization(init).

init:-
  absolute_file_name('fact.db', File, [access(write)]),
  db_attach(File, []).

You can now add/remove facts using assert_fact/2, retract_fact/2, and retractall_fact/2.

Upon exiting Prolog the asserted facts are automatically saved to fact.db.

Example usage:

$ swipl my_facts.pl
?- assert_fact(some(fact), some(other,fact)).
true.
?- halt.
$ swipl my_facts.pl
?- fact(X, Y).
X = some(fact),
Y = some(other, fact).

If what you're after is just to get a list of certain facts asserted with a predicate, then mbratch's suggestion will work fine. But you may also want to save the state of your program in general, in which case you can use qsave_program/2. According to the swi docs, qsave_program(+File, +Options)

Saves the current state of the program to the file File. The result is a resource archive containing a saved state that expresses all Prolog data from the running program and all user-defined resources.

Documentation here http://www.swi-prolog.org/pldoc/man?section=runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!