【发布时间】:2016-09-22 05:38:48
【问题描述】:
我最近正在学习 Prolog,但无法让它按照我想要的方式运行。举个例子,我的任务是创建一个 Prolog Psychiatrist,它接受输入并将其转化为一个问题,即“我认为我不舒服”变成了“你为什么认为你不舒服?”。
但是,到目前为止,我的代码在退出时会生成一个无限循环。它在 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 output infinite-loop