3

I'm kinda new in Prolog and I'm using SWI-Prolog v6.6 to storage asserts in a *.pl file.

:- dynamic fact/2.

assert(fact(fact1,fact2)).

With the code above I can make asserts and it works fine, but the problem is when I close SWI-Prolog and I open the *.pl file again, the asserts I've made are gone...

Is there a way to make asserts and those get stored even if I exit the Prolog process?

Sorry about my bad english and Thanks! (:

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
xzrudy
  • 93
  • 1
  • 8
  • 1
    You have to explicitly write them to a file. They are persistent in memory, but when Prolog closes, everything is gone unless written to a file. – lurker Apr 05 '14 at 22:08
  • See, for example, http://stackoverflow.com/questions/2921937/appending-facts-into-an-existing-prolog-file, which uses the Edinburgh style I/O. – lurker Apr 05 '14 at 22:25

2 Answers2

10

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).
Wouter Beek
  • 3,307
  • 16
  • 29
3

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

Shon
  • 3,989
  • 1
  • 22
  • 35