Search code examples
prolog

How to use predicate value inside another predicate


My rules looks like this.

cars(ferrari, 320).
cars(ford, 270).
cars(mercedes, 280).
cars(toyota, 220).

I have a predicate in which I want to check if a specific car is faster.

is_faster(Carmodel):-
  cars(Carmodel,X),
  X > 250.

So when I write is_faster(ferrari), I expect to get true but when I use trace. I find out that the X value is not returned?

In my console if I do

cars(ferrari,X).
X = 320.
true.

So what is wrong with this, why I'm not getting the value inside my predicate.


Solution

  • I think this should really be a comment, but comments don't allow formatted text, which is needed to illustrate trace.

    When you load your code as you have stated it in SWI Prolog you should see this:

    2 ?- trace.
    true.
    
    [trace] 2 ?- is_faster(ferrari).
       Call: (8) is_faster(ferrari) ? creep
       Call: (9) cars(ferrari, _5220) ? creep     % Anonymous variable _5220 (instead of X)
       Exit: (9) cars(ferrari, 320) ? creep       % Found 320 for ferrari
       Call: (9) 320>250 ? creep
       Exit: (9) 320>250 ? creep
       Exit: (8) is_faster(ferrari) ? creep
    true.
    
    [trace] 3 ?-