PROLOG - 条件函数 [英] PROLOG - conditional function
问题描述
如何列出男女学生都注册的课程的名称.
How can I list list the names of courses having both male and female students registered for them.
代码:
/*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).
不幸的是,我无法无法实现正确的查询或条件来打印男女学生都注册的课程的名称列表为他们
Unfortunately, I can not achieve the right query or conditional to print the list the names of courses having both male and female students registered for them
推荐答案
使用 Prolog,将其视为一个逻辑语句:
With Prolog, think of it as a logical statement:
C
是一个有男学生和女学生的班级if has_male_students(C) 和 has_female_students(C)
C
is a class with both male and female students if has_male_students(C) and has_female_students(C)
您可以将其编写如下,将 :-
运算符视为 if:
You can write that as follows, thinking of the :-
operator as the if:
has_both_mf(C) :- has_gender(C, male), has_gender(C, female).
现在你只需要弄清楚具有特定性别的类的逻辑:
Now you just have to figure the logic for a class having a specific gender:
C
有性别 G
学生 if C
有 id CourseId
, studentId 参加课程 CourseId
,学生 ID 是性别 G
.
C
has genderG
students ifC
has idCourseId
, student Id takes courseCourseId
and student Id is genderG
.
你可以这样写:
has_gender(C, G) :-
course(CourseId, C),
takes(StudentId, CourseId),
student(_, StudentId, _, G).
现在你会得到重复,因为一个班级可能有多个男学生和女学生,所以给定的班级以不止一种方式解决相同的逻辑.我将把它作为一个练习来获得独特的解决方案.一种简单的方法是在 SWI Prolog 中使用 once/1
谓词(您可以在文档中找到它).
Now you're going to get repeats because a class may have multiple casts of male and female students, so a given class solves the same logic in more than one way. I'll leave that as an exercise to get unique solutions. An easy way is to use the once/1
predicate in SWI Prolog (you can find it in the documentation).
这篇关于PROLOG - 条件函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!