update/add 数据库中事实的最佳方式?

Best way to update/add fact in the db?

说我有这样的事实:

fact(abc,2).

我想要这样的东西(伪代码):

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

我尝试了两种不同的方法。 第一个我不太喜欢:

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

第二个不行:

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

因为当Fact不成功时Amt没有被实例化,所以总是得到NewAmt is Val.

我会写

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