ELIZA这是典型的聊天机器人 .
它并不真正“理解”对话框的语法结构,但可能是一个好的开始 .
非常simple example在SWISH . 这是一些代码在我的HD上睡觉(IIRC,它来自Clocksin - Mellish,移植到SWI-Prolog) .
eliza :-
write('? '), read_word_list(Input), eliza(Input), !.
eliza([bye]) :-
write('Goodbye. I hope I have helped you'), nl.
eliza(Input) :-
pattern(Stimulus, Response),
match(Stimulus, Dictionary, Input),
match(Response, Dictionary, Output),
reply(Output),
!, eliza.
match([N|Pattern], Dictionary, Target) :-
integer(N), lookup(N, Dictionary, LeftTarget),
append(LeftTarget, RightTarget, Target),
match(Pattern, Dictionary, RightTarget).
match([Word | Pattern], Dictionary, [Word | Target]) :-
atom(Word), match(Pattern, Dictionary, Target).
match([], _Dictionary, []).
pattern([i,am,1],[how,long,have,you,been,1,'?']).
pattern([1,you,2,me],[what,makes,you,think,i,2,you,'?']).
pattern([i,like,1],[does,anyone,else,in,your,family,like,1,'?']).
pattern([i,feel,1],[do,you,often,feel,that,way,'?']).
pattern([1,X,2],[can,you,tell,me,more,about,your,X,'?']) :- important(X).
pattern([1],[please,go,on]).
important(father).
important(mother).
important(son).
important(sister).
important(brother).
important(daughter).
reply([Head | Tail]) :-
write(Head), write(' '), reply(Tail).
reply([]) :- nl.
lookup(Key, [(Key, Value) | _Dict], Value).
lookup(Key, [(Key1, _Val1) | Dictionary], Value) :-
Key \= Key1, lookup(Key, Dictionary, Value).
read_word_list(Ws) :-
read_line_to_codes(user_input, Cs),
atom_codes(A, Cs),
tokenize_atom(A, Ws).
编辑回答评论...
好吧,那段代码是由Prolog大师编写的,而不是我:)所以,我们应该尝试理解它......这两个子句实现了'incremental dictionary',数据结构不完整 . 它们在刺激和响应之间绑定任意短语,并且是ELIZA这种紧凑编码的关键(原始程序并非如此简单,尽管......) . 要遵循用法,Prolog调试是可能的:
?- leash(-all),spy(lookup).
?- eliza.
? i am happy
* Call: (12) lookup(1, _G4620, _G4621)
* Exit: (12) lookup(1, [(1, _G4616)|_G4613], _G4616)
* Call: (15) lookup(1, [(1, [happy])|_G4613], _G4645)
* Exit: (15) lookup(1, [(1, [happy])|_G4613], [happy])
how long have you been happy ?
? i think you hate me
* Call: (14) lookup(1, _G4821, _G4822)
* Exit: (14) lookup(1, [(1, _G4817)|_G4814], _G4817)
* Call: (16) lookup(2, [(1, [i, think])|_G4814], _G4834)
* Call: (17) lookup(2, _G4814, _G4834)
* Exit: (17) lookup(2, [(2, _G4829)|_G4826], _G4829)
* Exit: (16) lookup(2, [(1, [i, think]), (2, _G4829)|_G4826], _G4829)
* Call: (19) lookup(2, [(1, [i, think]), (2, [hate])|_G4826], _G4858)
* Call: (20) lookup(2, [(2, [hate])|_G4826], _G4858)
* Exit: (20) lookup(2, [(2, [hate])|_G4826], [hate])
* Exit: (19) lookup(2, [(1, [i, think]), (2, [hate])|_G4826], [hate])
what makes you think i hate you ?
...
您可以看到关联列表的尾部在退出时是空闲的,因此根据需要扩展了Dictionary . 巧妙地使用不完整的数据结构 . 参见“Prolog的艺术”第15章