Search code examples
prologprolog-assert

Best way to update/add fact in the db?


Say I have facts like this :

fact(abc,2).

I want something like this (pseudo code) :

fact_update(Functor,Name,AddToValue) :- 
  if Fact_exist then update_fact : NewVal is CurrentValue + AddToValue
  else create_new_fact : Functor(Name,AddToValue)

I've tried 2 different ways. The first I don't like very much :

 fact_add(Functor,Name,Val) :-
    Fact =.. [Functor, Name, Val],
    assert(Fact),
    say([fact, Fact]).
 fact_update(true, Functor,Name,Val) :-
    Fact =.. [Functor, Name, Amt],
    Fact,
    retractall(Fact),
    X is Amt + Val,
    fact_add(Functor,Name,X). %% retractall??
 fact_update(false,Functor,Name,Val) :-
    fact_add(Functor,Name,Val).

The second does not work :

fact_update(Functor,Name,Val) :-
   Fact =.. [Functor, Name, Amt],
   (
      Fact -> retractall(Fact)
   ;
      (
         (nonvar(Amt) -> NewAmt is Amt + Val ; NewAmt is Val),
         Fact =.. [Functor, Name, NewAmt],
         assert(Fact)
      )
   ),
   say([upd_fact, Fact]).

Because when Fact does not succeed Amt is not instantiated, so I always get NewAmt is Val.


Solution

  • I would write

    fact_update(Functor,Name,AddToValue) :- 
      Curr =.. [Functor,Name,CurrVal],
      (   retract(Curr)
      ->  NextVal is CurrVal+AddToValue,
          Next =.. [Functor,Name,NextVal]
      ;   Next =.. [Functor,Name,AddToValue]
      ),
      assertz(Next).