1

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.

SQB
  • 3,926
  • 2
  • 28
  • 49
sten
  • 7,028
  • 9
  • 41
  • 63

1 Answers1

2

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).
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • clever, I didn't tought I can use retract() fail/success as condition.. will give it a try. thanks – sten Nov 22 '15 at 21:16