2015-11-22 84 views
1

說我有事實是這樣的:在數據庫中更新/添加事實的最佳方法?

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

回答

2

我會寫

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

聰明,我沒因子評分我可以使用回退()失敗/成功作爲條件..會試試看。謝謝 – user1019129

相關問題