shaungus
shaungus

Reputation: 129

Prolog - call a rule with fact

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

I'm 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. I'm 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:

Upvotes: 1

Views: 1608

Answers (1)

svick
svick

Reputation: 244918

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

Upvotes: 1

Related Questions