Search code examples
prologpersistence

Persistence of facts in Prolog


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! (:


Solution

  • 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).