我最近在學習Prolog,並且很難讓它運行得如何。作爲一個例子,我已經設定了一個任務來創建一個Prolog精神病學家,它將輸入信息轉化爲一個問題,我「我認爲我不適」變成了「你爲什麼認爲你不舒服?」。Prolog寫入無限循環
但是,到目前爲止,我的代碼在退出時會生成一個無限循環。它在另一個未綁定的變量上調用printSentence的重做,並將其添加到輸出列表的末尾,並永遠這樣做。
這裏是我的代碼:
/* printSentence simply calls the in-built Prolog write function. */
printSentence([]) :- write('?').
printSentence([H|T]) :- write(H),write(' '), printSentence(T).
answer([], _) :- write('Why are you silent? Talk to me.').
answer(Input, Output) :- thinkMatch(Input, Output), printSentence(Output).
thinkMatch(['I', 'think'|Rest], ['Why', 'do', 'you', 'think'|SwitchedRest]) :- switchPronouns(Rest, SwitchedRest).
switchPronouns([], _).
switchPronouns([H|T], [R|SwitchedRest]) :- switchWord(H, R),switchPronouns(T, SwitchedRest).
switchWord('I', 'you').
switchWord('myself', 'yourself').
switchWord('am', 'are').
switchWord('you', 'me').
switchWord('yourself', 'myself').
switchWord(H, H).
輸入,
answer(['I', 'think', 'therefore', 'I', 'am'],Output).
產生這些結果事情永遠
?- Input = ['I', 'think', 'therefore', 'I', 'am'],answer(Input, Output).
Why do you think therefore you are ?
Input = ['I', think, therefore, 'I', am],
Output = ['Why', do, you, think, therefore, you, are] ;
_G4395 ?
Input = ['I', think, therefore, 'I', am],
Output = ['Why', do, you, think, therefore, you, are, _G4395] ;
_G4398 ?
Input = ['I', think, therefore, 'I', am],
Output = ['Why', do, you, think, therefore, you, are, _G4395, _G4398] ;
_G4401 ?
Input = ['I', think, therefore, 'I', am],
Output = ['Why', do, you, think, therefore, you, are, _G4395, _G4398|...]
道歉,如果這件事情小啞巴我已經還沒有完全掌握Prolog的內在陰謀。
在此先感謝。
這是一個非常完整的答案非常感謝!這個回答有助於我理解Prolog的工作原理 – SHolmes