Prolog查询练习 - 初学者

时间:2014-03-17 22:09:05

标签: prolog

我是Prolog的佼佼者,我需要一些这方面的帮助,这是提供的知识库:

album(‘R. Stevie Moore’, ‘Manuscription’).   
album(‘Lane Steinberg’, ‘Manuscription’).  
album(‘R. Stevie Moore’, ‘The Yung & Moore Show’).  
album(‘Yukio Yung’, ‘The Yung & Moore Show’).  
album(‘Jessie Evans’, ‘Autonervous’).  
album(‘Bettina Koster’, ‘Autonervous’).  
album(‘Lucia Pamela’, ‘Walkin on the moon’).  
album(‘Shooby Taylor’, ‘The Human Horn’).  
album(‘Tiny Tim’, ‘God Bless Tiny Tim’).  
album(‘The Legendary Stardust Cowboy’, ‘Rock-It to Stardom’).  
vinil(‘Rock-It to Stardom’).  
vinil(‘Walking on the Moon’).  
cd( ‘God Bless Tiny Tim’).  
cd(‘Walking on the Moon’).  
cd(‘Autonervous’).  
cd(‘Manuscription’).  
cassette(‘The Human Horn’).  
cassette(‘The Yung & Moore Show’).  
mp3(‘Walkin on the Moon’).  

我需要制作一个查询,将只返回由一位音乐家制作的所有专辑 谢谢你的帮助:)

2 个答案:

答案 0 :(得分:2)

在评论中,您提供了代码album(X,B),album(Y,C), B \= C.实际上,这距离正确的解决方案并不太远。

正确的解决方案可能是:

one_musician_album(X) :-
    album(A, X), 
    \+ (album(B, X), A \= B).

谓词的含义是:如果这张专辑是由一些音乐家A创作的,那么专辑X是一张“单音乐专辑”,并且不可能找到一位不同的音乐家B创作专辑X.

试运行:

?- one_musician_album(X).
X = 'Walkin on the moon' ;
X = 'The Human Horn' ;
X = 'God Bless Tiny Tim' ;
X = 'Rock-It to Stardom'.

要获得所有答案,您必须输入';'在每个答案之后。

也许您不需要这样做,但可以使用findall在列表中获取所有答案:

?- findall(X, one_musician_album(X), Albums).
Albums = ['Walkin on the moon', 'The Human Horn', 'God Bless Tiny Tim', 'Rock-It to Stardom'].

答案 1 :(得分:2)

这是一个概括,基于内置bagof / 3的“所有解决方案”。

请注意

?- bagof(A, album(A,T), As).
T = 'Autonervous',
As = ['Jessie Evans', 'Bettina Koster'] ;
T = 'God Bless Tiny Tim',
As = ['Tiny Tim'] 
....

然后,限制作者(As)成为单个元素的列表,我们获得一个作者的专辑

?- bagof(A, album(A,T), [A]).
A = 'Tiny Tim',
T = 'God Bless Tiny Tim' ;
...

然后,我们可以使用findall / 3,就像Sergey的好答案一样,或者再次使用bagof / 3,使用明确的量化:

?- bagof(T, A^bagof(A, album(A, T), [A]), Ts).
Ts = ['God Bless Tiny Tim', 'Rock-It to Stardom', 'The Human Horn', 'Walkin on the moon'].