9.0 Prolog: Q1 Find The Total Cost of Items
9.0 Prolog: Q1 Find The Total Cost of Items
0 Prolog
Q1
facts
Rule
costofitem(crisps, 190).
totalcost([], 0).
% trivial branch
totalcost([Item|Rest], Price) :- % recursive branch
costofitem(Item, Itemprice),
totalcost(Rest, PriceOfRest),
Price is Itemprice + PriceOfRest.
Query
Q2
facts
costofitem(cornflakes, 230).
costofitem(cocacola, 210).
costofitem(chocolate, 250).
Rule
costofitem(crisps, 190).
count([],0).
count([Item|Rest],Total):-costofitem(Item,Itemprice),count(Rest,Trest),Total
Trest+1.
%count(List,TL):-length List
Query
is
Constant (in small letters):- data type matches with itself or Variable (capital
letters)
Variable(in Capital Letters):-data type matches with anything
Structure(in small letter):-data type matches itself or variable consider following:o Name of structure must be same
o No of components must be same
o Data type must be same
Q1
Rule:
costofitem(cocacola, 210).
costofitem(chocolate, 250).
costofitem(crisps, 190).
Query
1 ?- totalcost([cornflakes,chocolate],X).
X = 480.
ExplanationSince in the above rule it is firstly matches with the facts. The totalcost here
takingthe List of itmes and the by the help of list constructor its first element and theremaining
element is separated the first element is stored into the item variable.And now this variable is
passed with fact and there is also one variable that will storethe price of the item that is pointed
by the item variable.The call to the fact matches with the above given fact if match found
successful thenthe price of that item is stored inside the Itemprice variable. And after that the
remaining part is again passed to the rule and the simila process continues till the list will not be
empty
Q2
Rule:count([],0).
count([Item|Rest],Total):-costofitem(Item,Itemprice),count(Rest,Trest),Total is
Trest+1.
%count(List,TL):-length List
Facts:
costofitem(cornflakes, 230).
costofitem(cocacola, 210).
costofitem(chocolate, 250).
costofitem(crisps, 190).
Query 2 ?- count([cornflakes,chocolate],X).
X = 2.
Explanation in this element in the list will iterate one by one through recursion and every time
whenever the rule is called the counter variable is incremented by 1 and finally it will
have the value that is equal to the number of items in the list