PROLOG - 条件函数

问题描述 投票:0回答:1

如何列出列出男女学生注册课程名称的列表。

码:

/*student(name,studnumb,age,sex)*/ 
student(braum,1234,22,male).
student(lux,7839,26,female).
student(ekko,1726,29,male).
student(kayle,1114,25,female).
student(darius,6654,36,male).
student(morgana,4627,20,female).
student(ashe,2563,25,female).
student(brand,9258,30,male).

findboys(GENDER):-
   student(_, IS, SY, GENDER),
   (  var(GENDER)->true
   ;  SY = male
   ),
   takes(IS, IT),
   teaches(TN,IT),
   writeln([TN,course(IS, _)]),
   fail
;  true.

/*takes(studnum,modnum)*/  
takes(1234,1111).
takes(7839,1111).
takes(1726,1111).
takes(1114,2345).
takes(6654,1111).
takes(4627,4588).
takes(2563,2222).
takes(9258,6534).

/*course(modnum,modname)*/ 
course(2222,maths).
course(2345,english).
course(1111,computerscience).
course(6654,spanish).
course(6789,antrophormism).
course(4588,teology).

不幸的是,我无法实现正确的查询或有条件地打印列表中有男女学生注册的课程名称

prolog
1个回答
1
投票

使用Prolog,将其视为一个逻辑陈述:

如果has_male_students(C)和has_female_students(C),C是男生和女生的课程

您可以如下编写,将:-运算符视为if:

has_both_mf(C) :- has_gender(C, male), has_gender(C, female).

现在,您只需要计算具有特定性别的类的逻辑:

C有性别G学生如果C有id CourseId,学生Id需要课程CourseId和学生Id是性别G

你可以这样写:

has_gender(C, G) :-
    course(CourseId, C),
    takes(StudentId, CourseId),
    student(_, StudentId, _, G).

现在你将要重复,因为一个班级可能有多个男女学生,所以一个给定的班级以不止一种方式解决相同的逻辑。我会把它作为练习来获得独特的解决方案。一种简单的方法是在SWI Prolog中使用once/1谓词(您可以在文档中找到它)。

© www.soinside.com 2019 - 2024. All rights reserved.