Prolog substitution

前端 未结 5 1345
囚心锁ツ
囚心锁ツ 2021-01-22 21:32

How can I replace a list with another list that contain the variable to be replaced. for example

rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x,         


        
5条回答
  •  忘掉有多难
    2021-01-22 21:51

    Let's improve this answer by moving the "recursive part" into meta-predicate find_first_in_t/4:

    :- meta_predicate find_first_in_t(2,?,?,?).
    find_first_in_t(P_2,X,Xs,Truth) :-
       list_first_suchthat_t(Xs,X,P_2,Truth).
    
    list_first_suchthat_t([]    ,_, _ ,false).
    list_first_suchthat_t([E|Es],X,P_2,Truth) :-
       if_(call(P_2,E),
           (E=X,Truth=true),
           list_first_suchthat_t(Es,X,P_2,Truth)).
    

    To fill in the "missing bits and pieces", we define key_pair_t/3:

    key_pair_t(Key,K-_,Truth) :-
       =(Key,K,Truth).
    

    Based on find_first_in_t/4 and key_pair_t/3, we can write assoc_key_mapped/3 like this:

    assoc_key_mapped(Assoc,Key,Value) :-
       if_(find_first_in_t(key_pair_t(Key),_-Value,Assoc),
           true,
           Key=Value).
    

    So, does the OP's use-case still work?

    ?- maplist(assoc_key_mapped([x-z,z-x,d-c]), [x,d,e,z,a,z,p], Rs).
    Rs = [z,c,e,x,a,x,p].                            % OK. same result as before
    

    Building on find_first_in_t/4

    memberd_t(X,Xs,Truth) :-                        % memberd_t/3
       find_first_in_t(=(X),_,Xs,Truth).
    
    :- meta_predicate exists_in_t(2,?,?).           % exists_in_t/3
    exists_in_t(P_2,Xs,Truth) :-
       find_first_in_t(P_2,_,Xs,Truth).
    

提交回复
热议问题