2012-10-15 128 views
0

我剛開始使用Prolog,我不明白如何使用多個謂詞。 例如,我必須解決以下問題:用列表中的所有元素替換列表中的值。 這是我設法到目前爲止寫代碼:Prolog,使用多個謂詞

domains 
    elem=integer 
    list=elem* 

predicates 
    %append to a list already created another list. There are 3 list parameters 
    %because I don't know other method 
    append (list,list,list) 
    %This will search the list (the first one) for the searched element and 
    %it is it will replace it with the list(the second one). The result will be 
    %kept in the third list. 
    add(list,list,elem,list) 

goal 
    add([1,2,3,2,1],[4,5],2,L), 
    write (L). 
clauses 
    add ([],[_],_,[]). 
    add ([A|L],L1,E,[A|L2]):- 
     add(L,L1,E,L2). 
    add ([E|L],L1,E,L2):- 
     add(L,L1,E,L2). 
    append([],[],L2). 
    append([],[X|L1],[X|L2]):- 
     append([],L1,L2). 

回答

1

append定義工作?我想應該是

append([], L, L). 
append([X|Xs], Ys, [X|Zs]):- 
     append(Xs, Ys, Zs). 

append斷言它的序言編程最基本的工具之一,更好地保持平時的行爲,或更改名稱...

相反的add,一個更好的名字可能是replace_elem_with_list。 要實現它,您應該迭代,檢查每個元素,並且當您找到需要替換的匹配時追加列表而不是複製元素。

喜歡的東西

% replace_elem_with_list(ToSearch, Replacement, SoughtElem, Result) 
replace_elem_with_list([E|Es], Replacement, E, Result) :- 
    !, replace_elem_with_list(Es, Replacement, E, Rs), 
    append(Replacement, Rs, Result). 

我會離開你另2例,你將需要支付(當元素不匹配和遞歸基地,這是類似追加)

的結果:

?- replace_elem_with_list([1,2,3,4,2,3,4],[a,b],2,L). 
L = [1, a, b, 3, 4, a, b, 3, 4].