Anthony Mifsud
Anthony Mifsud

Reputation: 132

Outputting Integers Greater than a given number in Prolog

I want to display all cars that were manucfactured after 1997.

How can it be done using nothing than queries?

These are the predicates

/* type(type reference, type of car) */

car_type(01,hatchback).
car_type(02,van).
car_type(03,off_road).

/* car(make ref, type ref, model, reg no, colour, year) */

car(01,01,escort,fsd127,blue,1999).
car(07,01,uno,tre333,blue,1996). 
car(02,03,discovery,uje777,red,1995).
car(03,01,starlet,uij236,green,1991).
car(01,02,transit,ski432,green,1991).
car(07,01,bravo,juy677,red,1998).

Below is the query I inputted.

?- car(_,TYPE_REF,_,_,_,(X@>1997)),
   car_type(TYPE_REF, TYPE_OF_CARS)

With the error being

false

I want to see the following output

Upvotes: 0

Views: 57

Answers (1)

gusbro
gusbro

Reputation: 22585

Your problem is that Prolog does not evaluate arguments inside queries (the procedure you are querying may evaluate them though, but is not what happens in your fact-based source).

So you are passing the term (X@>1997) as the last argument to car/6 which will not unify with any fact.

You may instead use a free variable to query every car and then constrain the value it is bound to:

?- car(_,TYPE_REF,_,_,_,Year), Year > 1997, car_type(TYPE_REF, TYPE_OF_CARS).
TYPE_REF = 1,
Year = 1999,
TYPE_OF_CARS = hatchback ;
TYPE_REF = 1,
Year = 1998,
TYPE_OF_CARS = hatchback.

Or you may start using CLP(fd) and add the constraint first:

?- Year #> 1997, car(_,TYPE_REF,_,_,_,Year), car_type(TYPE_REF, TYPE_OF_CARS).
Year = 1999,
TYPE_REF = 1,
TYPE_OF_CARS = hatchback ;
Year = 1998,
TYPE_REF = 1,
TYPE_OF_CARS = hatchback.

Upvotes: 1

Related Questions