序言:用复合术语将一个原子替换为其他原子 [英] Prolog: Replace an atom by other atom in compound terms

查看:103
本文介绍了序言:用复合术语将一个原子替换为其他原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的序言程序,该程序应将一个原子替换为另一个原子.该程序可以将复杂的函子作为输入,并将所有原子替换为另一个原子.

I am trying to write a simple prolog program which should replace an atom by another atom. The program can take complex functor as an input and would replace all the atoms by another atoms.

例如在下一个术语中,我只想在遇到叶子(即不是函子名称)的地方用ax替换atom a.

e.g. In the below term, I want to replace atom a by ax only where I encounter a leaf (i.e. not a functor name).

replace(put(a,table,aside(a(dont,replace),a)),X).

应该产生输出的

X = put(ax,table,aside(a(dont,replace),ax));
false.

在上面的输出中,除函子名称之外的所有地方都将a替换为ax.在某种程度上,所有的叶子都被替换了.但不是内部节点.

In the above output, replaced a with ax everywhere except the functor name. In a way all the leaves are replaced. But not internal nodes.

我已尝试关注

replace([],[]).
replace([H | T], [H1 | T1]):-
        (
        atom(H), (H == a)  %If it's an atom and equal to a, then replace H1 with ax.
        -> H1 = ax, replace(T, T1)  %and recursively follow the same for T.
        ; H1 = H, T1 = T, replace(T, T1)  %else keep things as it is and recurse.
        ).
replace(L, R):-
        functor(L, F1, A1),    %if it's a functor then don't do anything, just follow
        functor(R, F1, A1),    %for the args of the functor.
        L =.. [F1 | Args1],
        R =.. [F1 | Args2],

        replace(Args1, Args2),!.

问题1.对于相同的输入,我收到浅输出

Problem 1. I receive shallow output for the same input

replace(put(a,table,aside(ad,a,toe)),X).
X = put(ax,table,aside(ad,a,toe)).

问题2.当函子的偶数发生变化时,我的谓词将失败.例如,

Problem 2. My predicate would fail when arity of the functor changes. For example,

replace(put(a,table,aside(a(dont,replace),a)),X).
Undefined predicate: substit/2

我意识到我的方法可能不是最好的方法. 有人可以帮助我解决问题或提出新的方法.

I realize my approach might not be the best one. Can someone please help me either fix the issues or suggest a new approach.

谢谢.

推荐答案

可以更简单地完成

replace(X,Y,X,Y) :- !.
replace(X,Y,S,R) :-
    S =.. [F|As], maplist(replace(X,Y),As,Rs), R =.. [F|Rs], !.
replace(_,_,U,U).

类似地,您的代码应简化很多

similarly, your code should be simplified a lot

replace([],[]).
replace([H | T], [H1 | T1]):-
        (  H == a   
        -> H1 = ax  
        ;  replace(H, H1) 
        ),
    replace(T, T1).
replace(L, R):-
        L =.. [F1 | Args1],
        replace(Args1, Args2),
        R =.. [F1 | Args2].

现在

?- replace(put(a,table,aside(a(dont,replace),a)),X).
X = put(ax, table, aside(a(dont, replace), ax)) 

?- replace(put(a,table,aside(a(dont,replace),a)),X).
X = put(ax, table, aside(a(dont, replace), ax)) 

这篇关于序言:用复合术语将一个原子替换为其他原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆