Prolog知识查询

时间:2017-01-13 10:34:04

标签: prolog

% A quiz team structure takes the form:
% team(Captain, Vice_captain, Regular_team_members).
% Captain and Vice_captain are player structures;
% Regular_team_members is a list of player structures.
% player structures take the form:
% player(First_name, Surname, details(Speciality,Recent_score)).

team(player(niall,elliott,details(history,11)),
     player(michelle,cartwright,details(fashion,19)),
          [player(peter,lawlor,details(science,12)),
          player(louise,boyle,details(current_affairs,17))]).

我已经获得了上面的数据库(我还没有复制所有人的条目,因为它太长了。)

我被要求获得任何副队长的姓氏,他的团队包括一名队长或一名专业科学的常规团队成员。

我可以使用下面的代码获得副队长的姓氏,但我不能只返回那些包括队长或常规团队成员的团队,他们的专业是科学。我需要添加什么才能做到这一点?

part_two(Surname):-
    team(_,player(_,Surname,_),_).

我还被要求获得任何队长的名字和姓氏,他们的常规队员人数不止一个且姓氏相同。

这是我到目前为止的尝试:

part_three(First_name,Surname):-
    team(Captain,_,Regular_team_members),
    first_name(Captain,First_name),
    surname(Captain,Surname),
    Regular_team_members=[_,_|_].

我只需要排除那些常规队员不具有相同姓氏的队长的详细信息。

2 个答案:

答案 0 :(得分:3)

part_two(Surname):-
    team(Captain, Vice_captain, Regular_team_members),
    surname(Vice_captain, Surname),
    member(Player, [Captain|Regular_team_members]),
    specialty(Player, science).

% 'abstract data structures' accessors
surname(player(_First_name, Surname, _Details), Surname).
specialty(player(_First_name, _Surname, details(Speciality, _Recent_score)), Speciality).

由于您无论如何要扫描Regular_team_members列表,寻找合适的约束,您可以获得一个更简单的程序'首先加入' Captain给其他玩家。

答案 1 :(得分:1)

你可以改变一下你已写的内容如下:

 part_two(Surname):-
    team(P,player(_,Surname,_),L), 
    ( P=player(_,_,details(science,_)) -> true ; member(player(_,_,details(science,_)),L) ).

示例:

数据库:

team(player(niall,elliott,details(history,11)),
     player(michelle,cartwright,details(fashion,19)),
          [player(peter,lawlor,details(history,12)),
          player(louise,boyle,details(current_affairs,17))]).


team(player(niall1,elliott1,details(science,11)),
     player(michelle1,cartwright1,details(fashion,19)),
          [player(peter,lawlor,details(history,12)),
          player(louise,boyle,details(current_affairs,17))]).

team(player(niall2,elliott2,details(history,11)),
     player(michelle2,cartwright2,details(fashion,19)),
          [player(peter,lawlor,details(science,12)),
          player(louise,boyle,details(current_affairs,17))]).



 team(player(niall3,elliott3,details(science,11)),
     player(michelle3,cartwright3,details(fashion,19)),
          [player(peter,lawlor,details(science,12)),
          player(louise,boyle,details(current_affairs,17))]).

现在查询:

?- part_two(X).
X = cartwright1 ;
X = cartwright2 ;
X = cartwright3.