user2945914
user2945914

Reputation:

Prolog how to use if / else in this way?

In Prolog, i want to use an if-else statement in the following way:

lecture(spanish,monday,at8).
lecture(french,monday,at8).
lecture(english,monday,at10).
lecture(german,tuesday,at8).

generatePossibleSchedulesWithTwoLectures(LectureA,LectureB):-
     lecture(LectureA,A,X),
     lecture(LectureB,B,Y),
     %If A of LectureA is equal to B of lectureB -> times must be un-equal
     % How to do implement the requirement of the line above here?

As a result, the function should generate schedules with two lectures which are not in the same time slot.

Upvotes: 2

Views: 396

Answers (1)

lurker
lurker

Reputation: 58244

You started by assuming, i want to use an if-else statement in the following way, but the logic of your problem doesn't describe an if-then-else condition. An if-then-else isn't the construct you want to achieve your goal of:

Generate schedules with two lectures which are not in the same time slot

Also, the Prolog if-then-else construct A -> B ; C removes the choice point you are after. For some detail on this, see the answer to, What's the meaning of Prolog operator '->'

What you really want is to say:

A schedule two lectures A & B is valid if Day1 and Time1 are a time slot for A, and Day2 and Time2 are a time slot for B, and time slots Day1-Time1 and Day2-Time2 are different.

If fact, to avoid duplicates and to keep the schedule in chronological order, we can enforce that the "first" time slot is earlier than the second. This translates to:

generate_possible_schedules_with_two_lectures(LectureA, LectureB):-
    lecture(LectureA, Day1, Time1),
    lecture(LectureB, Day2, Time2),
    dif(LectureA, LectureB),   % don't schedule the same class
    Day1-Time1 @< Day2-Time2   % timeslots in order, and different

We simplify the time slot comparison by forming a term A-B with the day and time. You could do the longer comparison, comparing the day and tie individually, replacing Day1-Time1 @< Day2-Time2 with (Day1 @< Day2 ; Day1 == Day2, Time1 @< Time2). In either case, you get the following results with your data:

?- generate_possible_schedules_with_two_lectures(A, B).
A = spanish,
B = german ;
A = french,
B = german ;
A = english,
B = spanish ;
A = english,
B = french ;
A = english,
B = german ;
false.

Upvotes: 2

Related Questions