gpt4 book ai didi

prolog - 如何将 if else 转换为 Prolog 中的完全声明式?

转载 作者:行者123 更新时间:2023-12-03 01:20:14 25 4
gpt4 key购买 nike

这是我的类问题之一。

Question

我能够使用一堆 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')
).

有人知道如何使其“完全声明式”吗?

最佳答案

如果解决代码中的冗余问题,从逻辑中提取数据,最终会得到更具声明性的代码。

因此,对数据结构进行编码,并提供一个能够提出问题并推断结果的“解释器”。

例如

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).

您可能希望将菜单专门用于仅用于 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
%

示例 session :

% /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 .

关于prolog - 如何将 if else 转换为 Prolog 中的完全声明式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41407226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com