Re: How to replace a term to the inside of an other term?
- From: student <logic4sure@xxxxxxxxx>
- Date: Wed, 24 May 2006 23:34:40 GMT
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Mika wrote:
Hello, I must define the following procedure:
substitute(T,TOLD,TNEW,T1)
T1 is the term in which the occurrences of term ground TOLD they have
been replaced with TNEW
ex. substitute(f(a,g(a)),a,b,T).
T= f(b,g(b))
I would begin by deciding what I meant by the word "term" in this
context. Here is a handy way of looking at terms in Prolog:
/*
Term =.. [ P | TL ]
- --------------------------------
a =.. [ a | [] ]
[] =.. [ [] | [] ]
f(1,2,3) =.. [ f | [1,2,3] ]
[1,2,3] =.. [ '.' | [1,[2,3]] ]
- --------------------------------
*/
This view of the matter suggests to me the following approach to the
problem at hand:
replace(T,A,B,T1) :-
T =.. [P|TL],
( P = A -> P1 = B ; P1 = P ),
replaceL(TL,A,B,TL1),
T1 =.. [P1|TL1].
where 'replaceL/4' simply applies 'replace/4' to each term in TL.
This description supplies answers to the sorts of questions that
I suspect you were probably asked to answer, such as
?- replace(a,a,b,T1).
T1 = b ;
No
?- replace([a],a,b,T1).
T1 = [b] ;
No
?- replace(f(1,g(2,[2,4,5])),4,h(999),T1).
T1 = f(1, g(2, [2, h(999), 5])) ;
No
but it also supplies (consistently) answers to some slightly more
general questions, such as
?- replace(f(1,f(2,f(3,[]))),f,'.',T1).
T1 = [1, 2, 3] ;
No
?- replace([1,2,3],'.',f,T1).
T1 = f(1, f(2, f(3, []))) ;
No
?- replace(f(1,f(2,f(3,[]))),f,g,T1).
T1 = g(1, g(2, g(3, []))) ;
No
Thus, though I doubt it is "the right answer",
I think it is an interesting one.
- --
billh
using the superb SeaMonkey 1.0.1 with enigmail on Debian 3.1 GNU/Linux
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFEdO2smuz1B9Tdo+wRArafAJ98ISRkAVFvHS8FpR/8fYwFwlYwkgCfWkMO
c+ExkyRDkYFIJgZWYjGe0J8=
=/taN
-----END PGP SIGNATURE-----
.
- Follow-Ups:
- Re: How to replace a term to the inside of an other term?
- From: Joachim Schimpf
- Re: How to replace a term to the inside of an other term?
- References:
- Prev by Date: Re: How to replace a term to the inside of an other term?
- Next by Date: Re: How to replace a term to the inside of an other term?
- Previous by thread: Re: How to replace a term to the inside of an other term?
- Next by thread: Re: How to replace a term to the inside of an other term?
- Index(es):