comp(engine,sparkplug,4,b).
comp(engine,cylinder,4,c).
comp(engine,valve,4,c).
comp(engine,crankshaft,1,c).
comp(cylinder,piston,1,c).
comp(cylinder,connectingrod,1,c).
comp(valve,gasket,1,b).
comp(valve,hanger,2,c).
comp(crankshaft,joint,8,c).
comp(piston,screw,2,b).
comp(piston,gasket,3,b).
comp(connectingrod,screw,4,b).
comp(connectingrod,bolt,4,b).
comp(hanger,screw,4,b).
comp(hanger,bolt,2,b).
comp(joint,screw,10,b).
comp(joint,bolt,20,b).

price(sparkplug,10).
price(screw,2).
price(gasket,3).
price(bolt,2).

lookfor(Prod,IL,FL,Factor) :- 
   findall([Pr1,Qty,Flag],comp(Prod,Pr1,Qty,Flag),CL),
   inquire(CL,IL,FL,Factor).

inquire([],List,List,_).
inquire([[Pr1,Qty,Flag]|TC],List,FL,Fact) :- Flag == c, !, 
    Fact1 is Fact * Qty, 
    lookfor(Pr1,List,ML,Fact1),
    inquire(TC,ML,FL,Fact).  
inquire([[Pr1,Qty,_]|TC],List,FL,Fact) :- member([Pr1,_],List), !, 
    update(List,ML,Pr1,Qty,Fact),
    inquire(TC,ML,FL,Fact).  
inquire([[Pr1,Qty,_]|TC],List,FL,Fact) :-
    Q1 is Qty * Fact, 
    add([Pr1,Q1],List,ML),
    inquire(TC,ML,FL,Fact).  

update([[N,Q1]|T],[[N,Q2]|T],N,Q,Fact) :- Q2 is Q1 + Q * Fact.
update([H|T],[H|T1],N,Q,Fact) :- update(T,T1,N,Q,Fact).

add(E,[],[E]).
add(E,[H|T],[E|[H|T]]).

member(H,[H|_]).
member(E,[_|T]) :- member(E,T).

costs(Prod,Cost) :- lookfor(Prod,[],FL,1), examine(FL,Cost).

examine([],0).
examine([[E,N]|T],Cost) :- price(E,Cost1), examine(T,Cost2), 
                           Cost is Cost1 * N + Cost2.