Search code examples
prologtext-manipulationfailure-slicenon-termination

Transforming a sentence creates an infinite loop - but how?


I can't figure out where this is going wrong. Please note that I am very new to Prolog and I'm sure I'm missing something - just no idea what that might be. Could anyone help me out please?

Thanks, here is my code:

printSentence([]).   
printSentence([W|[]]) :-
    write(W),
    write('.'),
    nl.  
printSentence([W|R]) :-
    write(W),
    write(' '),
    printSentence(R).

transform([], Result).  
transform([Word|Rest], Result) :-
    replace(Word, Replacement),
    append(Result, Replacement, NewResult),
    transform(Rest, NewResult).

replace(my, your).
replace(i, you).
replace(you, me).
replace(am, are).
replace(Word, Word).

test :-
    X = [you, are, my, only, hope],
    transform(X, Result),
    printSentence(Result).

Solution

  • This should work. Notice you had a singleton in transform([],Result). Also, append doesn't work in the way you tried to use it, but you were on the right track generally.

    transform([], []).
    
    transform([Word|Rest], [Replacement|RestOfResult]) :-
        replace(Word, Replacement),
        transform(Rest, RestOfResult).