首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >prolog,用户选择咖啡菜单

prolog,用户选择咖啡菜单
EN

Stack Overflow用户
提问于 2018-11-19 03:15:21
回答 1查看 960关注 0票数 1

你能帮我写咖啡菜单吗?

这是我尝试过的。

代码语言:javascript
运行
复制
  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*/

我的方法是正确的还是更好的,创建一个列表,然后用户通过键入选择咖啡的名称?

像这样添加菜单

代码语言:javascript
运行
复制
    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).
EN

回答 1

Stack Overflow用户

发布于 2018-11-19 05:04:01

这里有一些简单的东西。

您首先需要一个选项和价格表,但在Prolog中,这些可以简单地作为事实来完成。

代码语言:javascript
运行
复制
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).

接下来,您需要决定谓词的参数,在本例中这很简单,输入的选项列表和输出的价格。

代码语言:javascript
运行
复制
coffeeOrder(Options,Price)

因为有一个选项列表,所以代码需要处理一个列表,对于初学者来说,最简单的方法之一就是使用递归调用。一组递归谓词遵循基本情况的模式

代码语言:javascript
运行
复制
% Do something when the list is empty.
coffeeOptions([], ... ). 

和一个用于处理递归处理列表的谓词

代码语言:javascript
运行
复制
% 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。

所以谓词是:

代码语言:javascript
运行
复制
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).

还有一个快速测试。

代码语言:javascript
运行
复制
?- coffeeOrder([moca,hot,grande],Price).
Price = 4.5.

所有代码都作为一个代码片段。

代码语言:javascript
运行
复制
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).
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53364550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档