你能帮我写咖啡菜单吗?
这是我尝试过的。
go :- hypothesize(Coffee),
write('Your order is : '),
write(Coffee),
write('and the price for your order = : ')
nl,
undo.
/* hypotheses to be tested */
hypothesize(moca) :- moca, !.
hypothesize(hotChocolate) :- hotChocolate, !.
hypothesize(latte) :- latte, !.
hypothesize(cappuccino) :- cappuccino, !.
/* rules */
moca :-
/* ask if you want hot or cold
* ask the size of the coffee*/我的方法是正确的还是更好的,创建一个列表,然后用户通过键入选择咖啡的名称?
像这样添加菜单
menu :- repeat,
write('pleaase, Choose the Coffe to order:'),nl,
write('1. Moca'),nl,
write('2. Latte'),nl,
write('3. Hot Choclate'),nl,
write('Enter your choice number please: '),nl,
read(Choice),
run_opt(Choice).发布于 2018-11-19 05:04:01
这里有一些简单的东西。
您首先需要一个选项和价格表,但在Prolog中,这些可以简单地作为事实来完成。
price(moca,2.0).
price(hotChocolate,1.5).
price(latte,2.5).
price(cappuccino,3.0).
price(cold,0.1).
price(hot,0.5).
price(short,1.0).
price(tall,1.5).
price(grande,2.0).
price(venti,2.5).
price(trenta,3.0).接下来,您需要决定谓词的参数,在本例中这很简单,输入的选项列表和输出的价格。
coffeeOrder(Options,Price)因为有一个选项列表,所以代码需要处理一个列表,对于初学者来说,最简单的方法之一就是使用递归调用。一组递归谓词遵循基本情况的模式
% Do something when the list is empty.
coffeeOptions([], ... ). 和一个用于处理递归处理列表的谓词
% Do something when the list is not empty.
coffeeOptions([H|T],PriceIn,PriceOut) :-
% do something with the head, H
coffeeOptions(T,NewPrice,PriceOut).在生成一个值时,通常需要一个辅助谓词来设置初始值,在这种情况下,初始成本为0.0。
所以谓词是:
coffeeOrder(Options,Price) :-
coffeeOptions(Options,0.0,Price). % This sets the initial price to 0.0.
% Do something when the list is empty.
coffeeOptions([],Price,Price).
% Do something when the list is not empty.
coffeeOptions([Option|T],Price0,Price) :-
price(Option,Cost),
Price1 is Price0 + Cost,
coffeeOptions(T,Price1,Price).还有一个快速测试。
?- coffeeOrder([moca,hot,grande],Price).
Price = 4.5.所有代码都作为一个代码片段。
coffeeOrder(Options,Price) :-
coffeeOptions(Options,0.0,Price).
coffeeOptions([],Price,Price).
coffeeOptions([Option|T],Price0,Price) :-
price(Option,Cost),
Price1 is Price0 + Cost,
coffeeOptions(T,Price1,Price).
price(moca,2.0).
price(hotChocolate,1.5).
price(latte,2.5).
price(cappuccino,3.0).
price(cold,0.1).
price(hot,0.5).
price(short,1.0).
price(tall,1.5).
price(grande,2.0).
price(venti,2.5).
price(trenta,3.0).https://stackoverflow.com/questions/53364550
复制相似问题