I have a prolog database file with lots of facts knowledge.pl. For example:
father_of(joe,paul).
father_of(joe,mary).
mother_of(jane,paul).
mother_of(jane,mary).
male(paul).
male(joe).
female(mary).
female(jane). % and so on.
This file is consulted (consult/1) every time my program is executed again.
I would like to be able to insert, modify and delete the facts I want (some of them directly, some others that meet some specific conditions) by writing or deleting directly within this database text file.
something like assertz, retract and retractall but modifying this text file so that the changes remain permanently there.
how can I do it?
you can either create the facts you want and write them to the (same) file or modify the database and then save it in the file.
the difference is that with the first approach you will have the db of the old file loaded while the second approach will change it during execution.
From the way you phrased the question I assume that you want to do the second; to do this you should:
1)declare all the predicates that you want to change as dynamic
2)assert,retract etc during execution
3)write the new database to the file. you can use listing/1
To write you can do something like:
or you can use some other io predicates. maybe using set_prolog_IO/3 would be the simplest way.
Now, if you wanted the first, you should construct the predicates (probably using the univ operator) or other string manipulation predicates and then write them to a file
EDIT:
there is listing/0 but that will list all the predicates loaded (something you might not want).
after some searching I found source_file/2; so you can do something like
note that source_file/2 requires the absolute filename. you can use absolute_file_name/2 to get it
the way source_file/2 formats the predicate is a bit weird (i was expecting something like foo/1) but it looks like you can give it to listing/1 and it works fine so you can do something like:
on the other hand, you can always have a list with the predicates you want to store somewhere in the file