J.D*_*Doe 7 declarative prolog logical-purity
这是我的课堂问题之一.
我能够用if-else创建我自己的Prolog程序,但我被告知我的程序并不是完全声明的,因为它是Prolog中最基本的原则之一.
这是我的代码
%start with :- go.
is_spicy :-
write('Do you want spicy? (yes/no)'),
read(Preference),
( Preference == yes -> recommend("Curry"); recommend("Kurma") ).
is_fry :-
write('Do you want fry food? (yes/no)'),
read(Preference),
( Preference == yes -> recommend("StirFry"); recommend("Chicken") ).
is_chili :-
write('Do you want chili? (yes/no)'),
read(Preference),
( Preference == yes -> recommend("Sambal"); recommend("Singgang") ).
recommend(Food) :- write('We recommend you '), write(Food).
go :-
write('Which food type do you prefer? (indian, chinese, malay): '),
read(FoodType),
(
FoodType == indian -> is_spicy;
FoodType == chinese -> is_fry;
FoodType == malay -> is_chili;
writeln('Please try again')
).
Run Code Online (Sandbox Code Playgroud)
任何人都知道如何使其"完全声明"?
如果您解决了代码中的冗余问题,并从逻辑中剔除了数据,那么最终将使用更多的声明性代码。
因此,对数据结构进行编码,并提供一个能够提出问题并推断后果的“解释器”。
例如
dt(food_type,
[indian -> dt(spicy, [ y -> curry, n -> curma ])
,chinese -> dt(fry, [ y -> stirFry, n -> chicken ])
,malay -> dt(chili, [ y -> sambal, n -> singgang ])
]).
interpreter(dt(About, Choices), Choice) :-
% present a menu for choices
% recurse on selected path
% when it reach a leaf, just unify
interpreter(Choice, Choice).
Run Code Online (Sandbox Code Playgroud)
您可能要专门针对仅y / n个选项的菜单,但这取决于您
编辑
呈现菜单并接受选择需要额外的逻辑编程,例如:
solve(Choice) :-
dt(About, Choices),
interpreter(dt(About, Choices), Choice).
% present a menu for choices
% recurse on selected path
interpreter(dt(About, Choices), Choice) :-
ask_user(About, Choices, ChoiceAbout),
interpreter(ChoiceAbout, Choice).
% when it reach a leaf, just unify
interpreter(Choice, Choice).
ask_user(About, Choices, Choice) :-
format('your choice about ~w ?~n', [About]), % show user the context of choice
forall(member(C->_,Choices), format(' ~w~n', [C])),
read(U),
memberchk(U->Choice, Choices).
% note: if memberchk above fails (user doesn't input a correct choice)
% you should provide an alternate ask_user here, otherwise ...
% just see what the code does
%
Run Code Online (Sandbox Code Playgroud)
会话示例:
% /home/carlo/Desktop/pl/choices compiled into choices 0.00 sec, 0 clauses
?- solve(C).
your choice about food_type ?
indian
chinese
malay
|: chinese.
your choice about fry ?
y
n
|: n.
C = chicken .
Run Code Online (Sandbox Code Playgroud)