查询prolog中的数据知识 [英] Querying a data knowledge in prolog

查看:22
本文介绍了查询prolog中的数据知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些这种形式的数据:

plot('侏罗纪公园','动作')plot('侏罗纪公园','戏剧')plot('侏罗纪公园','冒险')情节('低俗小说",'复古')情节('低俗小说','犯罪')....

其中 plot(X,Y) X 是一部电影,Y 是这种电影类型.

我想做的是查询此数据库并获取具有 3 个相同类型的所有电影.例如,如果有另一部电影是动作、戏剧、冒险,我希望它与侏罗纪公园配对.到目前为止我所做的:

predic(X,Y,Z,Z2,Z3):-绘图(X,Z),绘图(Y,Z),X \ = Y,plot(X,Z2), plot(Y,Z2), X \= Y, Z\=Z2,plot(X,Z3), plot(Y,Z3), X \= Y, Z\=Z3,Z2\=Z3

问题是这可能会返回多个移动 (X,Y) 实例(我希望它只返回一个),因为它返回 Z,Z2,Z3 之间的所有可能组合.它将返回(Jurassic Park,Jurassic World,action,adventure,drama),同时返回(Jurassic Park,Jurassic World,action,drama,adventure).>

那么,在找到满足谓词需要的 Z,Z2,Z3 的第一个组合后,我如何才能停止查询?我不能使用 "!" 因为我希望此查询返回具有 3 种常见类型而不仅仅是 1 种类型的所有可能的电影对.

解决方案

您可以在 Zi 条款中强制执行顺序,通过添加约束 Zi @i+1.因此,我们在这里使用 (@<)/2 谓词 [swi-doc],根据条款检查标准顺序:

predic(X, Y, Z1, Z2, Z3) :-绘图(X,Z1),绘图(Y,Z1),X \= Y,绘图(X,Z2),绘图(Y,Z2),Z1@,绘图(X,Z3),绘图(Y,Z3),Z2@.

如果您只对相似的两部电影的不同集感兴趣,您可以使用 distinct/1 元谓词:

predic(X, Y) :-预测(X,Y,_,_,_).相似(X,Y): -distinct(predic(X, Y)).

Let's say i have some data in this form:

plot('Jurrassic Park",'action')
plot('Jurrassic Park",'drama')
plot('Jurrassic Park",'adventure')
plot('pulp fiction",'retro')
plot('pulp fiction",'crime')
....

where in plot(X,Y) X is a movie and Y is this movies genre.

What i would like to do is query this database and get all the movies that have 3 equal genres. For example if there is another movie that is action,drama,adventure i would like it to be paired with Jurassic park.What i have done so far:

predic(X,Y,Z,Z2,Z3):-
   plot(X,Z), plot(Y,Z), X \= Y,
   plot(X,Z2), plot(Y,Z2), X \= Y, Z\=Z2,
   plot(X,Z3), plot(Y,Z3), X \= Y, Z\=Z3,Z2\=Z3

The problem is that this may return multiple instances of moves (X,Y)(i want it to return just one) because it returns all the possible combinations between Z,Z2,Z3.It will return (Jurassic Park,Jurassic World,action,adventure,drama) and it will also return (Jurassic Park,Jurassic World,action,drama,adventure).

So how could i make my query stop after finding the 1st combination of Z,Z2,Z3 which satisfies the predicates needs? I can't use "!" because i want this query to return all the possible pairs of movies with 3 common genres and not just 1.

解决方案

You can enforce order in the terms Zi, by adding constraints Zi @< Zi+1. Here we thus use the (@<)/2 predicate [swi-doc], that checks the standard order on terms:

predic(X, Y, Z1, Z2, Z3) :- 
    plot(X, Z1), plot(Y,Z1),
    X \= Y,
    plot(X, Z2), plot(Y,Z2),
    Z1 @< Z2,
    plot(X, Z3), plot(Y,Z3),
    Z2 @< Z3.

If you are only interested in distinct sets of two movies being similar, you can make use of the distinct/1 meta-predicate:

predic(X, Y) :-
    predic(X, Y, _, _, _).

similars(X, Y) :-
    distinct(predic(X, Y)).

这篇关于查询prolog中的数据知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆