开发者

Prolog - call a rule with fact

开发者 https://www.devze.com 2023-01-21 11:57 出处:网络
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

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开发者_如何学Go([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).


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

精彩评论

暂无评论...
验证码 换一张
取 消