How to replace a term to the inside of an other term?



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))

.