Prolog substitution

前端 未结 5 1277
囚心锁ツ
囚心锁ツ 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

    You should attempt to keep the code simpler than possible:

    rep([], _, []).
    rep([X|Xs], Vs, [Y|Ys]) :-
       ( memberchk(X=V, Vs) -> Y = V ; Y = X ),
       rep(Xs, Vs, Ys).
    

    Of course, note the idiomatic way (thru memberchk/2) to check for a variable value.

    Still yet a more idiomatic way to do: transforming lists it's a basic building block in several languages, and Prolog is no exception:

    rep(Xs, Vs, Ys) :- maplist(repv(Vs), Xs, Ys).
    repv(Vs, X, Y) :- memberchk(X=V, Vs) -> Y = V ; Y = X .
    

提交回复
热议问题