PROLOG - conditional function

2019-08-24 16:52发布

How can I list list the names of courses having both male and female students registered for them.

CODE:

/*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
1条回答
放我归山
2楼-- · 2019-08-24 17:13

With Prolog, think of it as a logical statement:

C is a class with both male and female students if has_male_students(C) and has_female_students(C)

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 has gender G students if C has id CourseId, student Id takes course CourseId and student Id is gender G.

You can write that as:

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

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).

查看更多
登录 后发表回答