Prolog insert, modify and delete facts on a separated database text file

前端 未结 2 1943
逝去的感伤
逝去的感伤 2021-01-13 22:37

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


        
2条回答
  •  北海茫月
    2021-01-13 22:57

    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:

    tell(knowledge),
    .....
    told.
    

    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

    findall(X,source_file(X,FileName),L).
    

    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:

    save(FileName):-
        absolute_file_name(FileName,Abs),
        findall(X,source_file(X,Abs),L),
        tell(FileName),
        maplist(listing,L),
        told.
    

    on the other hand, you can always have a list with the predicates you want to store somewhere in the file

提交回复
热议问题