序言,用户选择咖啡菜单

时间:2018-11-18 19:15:21

标签: list menu prolog

我是Prolog课程的初学者,我正在尝试编写代码,以允许用户选择咖啡,然后询问是否冷热,然后询问咖啡的大小来计算价格。我在网上查看有关如何开发该程序的说明,但是我觉得它与示例中所需要的有所不同:[动物识别] [1]。你能帮我写咖啡菜单吗?

这是我尝试过的。

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

1 个答案:

答案 0 :(得分:0)

这很简单。

您首先需要一张期权和价格表,但是在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).