首页 > 解决方案 > 在Prolog中输出大于给定数字的整数

问题描述

我想展示 1997 年以后生产的所有汽车。

除了查询之外,如何才能做到这一点?

这些是谓词

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

以下是我输入的查询。

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

错误是

错误的

我想看到以下输出

标签: prolog

解决方案


您的问题是 Prolog 不会评估查询中的参数(您正在查询的过程可能会评估它们,但不是基于事实的源中发生的情况)。

因此,您将术语(X@>1997)作为最后一个参数传递car/6,它不会与任何事实相统一。

您可以改为使用自由变量来查询每辆车,然后限制它绑定到的值:

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

或者您可以开始使用CLP(fd)并首先添加约束:

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

推荐阅读