views:

54

answers:

1

TL;DR: Need help calling a rule with a fact
I´ve started out with prolog, coming from C and got stuff working... until they evidently got broken. I´m writing a small car-paint program for myself as I´m learning this new language

Im trying to call a rule with a fact (is this possible?), what I want to do is use one fact "cars" and another fact "paint" to make one big list consisting of all the cars in all the different paints. Im having trouble making the code work as I want...have a look

I´ve got the facts:

cars([ferrari, bmw, ford, jaguar]).  
paints([red, white, blue, yellow]).  

/*Now I wanted to loop through each car, eachtime printing 
out the different paint combinations of that car:  */

start:- loop_cars(cars(C)).  /*starts loop_cars with all the cars e.g [ferrari...]*/
                             /*but it false here, even if C = [ferrari...]*/
loop_cars([]).  
loop_cars([Ca|Rest]):-  
    loop_paints(Ca,paints(P)),  /*The car is sent off for a paint job,...*/
    loop_cars(Rest).            /*...(cont from above) same false here as before*/

loop_paints(_,[]).  
loop_paints(Ca,[Pa|Rest]):-  /*This works*/
    write([Ca,Pa]),  /*Writes it like "[ferrari, white] [ferrari, blue] ..."*/
    loop_paints(Ca,Rest).  

So I guess I need help solving two problems:

  • How do i pass the contents of the facts cars and paints to the two loops?
  • A "garage" to put all the combinations in. Garage being a big list consisting of small 2-items-lists (the car and paint).

Grateful of assistance

+1  A: 

You can do it like this:

start :- cars(C), loop_cars(C).

First, “assign” (I think it's called “unify” in Prolog terminology) the list of cars to the variable C and then call loop_cars for this list. Similarly with paints.

If you want to store the result in a variable, you have to add an “output” parametr to your predicates:

loop_paints(_,[],[]).  
loop_paints(Ca,[Pa|Rest],[Res|ResRest]):-
    Res = [Ca,Pa],
    loop_paints(Ca,Rest,ResRest).
svick
Thanks, that unifying thing worked. The storing not so much
shaungus