I'm doing some past exam papers for practice for my exam, and I've come across a question that I'm not quite sure how to tackle:
I know I've got to use the "univ" function to break up the term into a list, and then recurse through that list and check if any of the elements in the list equal the term we want to replace. However, I'm a bit lost with double recursing when the list contains another complex term that we have to break down further. My attempt so far is as follows:
complexTerm(X) :- nonvar(X), functor(X, _, A), A > 0.
replace(Term, Subterm, Subterm1, Term1) :-
Term =.. [H|T],
replaceSub([H|T], Subterm, Subterm1, Term1)
replaceSub([], Subterm, Subterm1, Term1).
replaceSub([H], Subterm, Subterm1, Term1) :-
atomic(X),
H == Subterm,
H = Subterm1.
replaceSub([H], Subterm, Subterm1, Term1) :-
complexTerm(H),
replace(H, Subterm, Subterm1, Term1).
replaceSub([H|T]) :- % not sure where to continue with this.
Any pointers would be much appreciated. Note that for the exam we can't use external modules.
Thanks for your time.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…