首页 文章

Prolog,使用多个谓词

提问于
浏览
0

我刚刚开始使用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 回答

  • 1

    你的 append 定义是否有效?我认为应该是

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

    append 谓词它是Prolog编程中最基本的工具之一,更好地保持通常的行为,或改变名称......

    而不是 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).
    

    我将告诉你另外两个你需要覆盖的情况(当元素不匹配和递归基数时,它们类似于追加)

    结果:

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

相关问题