2012-10-15 6 views
0

방금 ​​Prolog로 작업하기 시작했으며 여러 술어로 작업하는 f}을 이해하지 못합니다. 예를 들어, 다음 문제를 해결해야합니다. 목록에서 다른 목록의 모든 요소로 값을 대체하십시오.여러 술어로 작업하는 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 정의가 작동합니까 : 이것은 내가 지금까지 작성하는 관리되는 코드는? 나는 add

대신

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

는 프롤로그 프로그래밍에서 가장 기본적인 도구 중 하나 년대 append 조건, 더 나은 일반적인 동작을 유지하거나 이름을 변경 ..., 더 좋은 이름이어야한다고 생각합니다 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). 

을 (요소가 일치하지 않는 경우와 유사하다 재귀 기지, 추가 할 때) 나는 당신이 충당해야하는 다른 두 사례를 떠날거야 결과 :

?- 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]. 
관련 문제