El Psy Congroo
El Psy Congroo

Reputation: 11

Prolog Outputting True and False

I have seen similar questions asked regarding prolog outputting true and false at the same time. People have suggested using the cut operator (!) or "once". I understand why prolog is producing true and false, and I understand how the cut operator works but I just don't know where to put it. Anyways this is my code(I wrote it on notepad++):

is_classroom_occupied(mon, 8, 8_348).
is_classroom_occupied(wed, 8, 8_348).
is_classroom_occupied(fri, 8, 8_348).
is_classroom_occupied(mon, 12, 9_285).
is_classroom_occupied(wed, 12, 9_285).
is_classroom_occupied(fri, 12, 9_285).
is_classroom_occupied(mon, 2, 8_247).
is_classroom_occupied(wed, 2, 8_247).
is_classroom_occupied(fri, 2, 8_247).
is_classroom_occupied(tu, 5, 8_348).
is_classroom_occupied(thu, 5, 8_348).

is_classroom_occupied(day, timeslot, location) :-
    is_classroom_occupied(mon, 8, 8_348),
    is_classroom_occupied(wed, 8, 8_348),
    is_classroom_occupied(fri, 8, 8_348),
    is_classroom_occupied(mon, 12, 9_285),
    is_classroom_occupied(wed, 12, 9_285),
    is_classroom_occupied(fri, 12, 9_285),
    is_classroom_occupied(mon, 2, 8_247),
    is_classroom_occupied(wed, 2, 8_247),
    is_classroom_occupied(fri, 2, 8_247),
    is_classroom_occupied(tu, 5, 8_348),
    is_classroom_occupied(thu, 5, 8_348).

The first half is a collection of facts that show the day, time, and room number of my classes, and the second part is a rule. Here is an example query:

 ?- is_classroom_occupied(mon, 8, 8_348).

and it outputs

true ;
false.

But I only want it to output the first result and ignore the rest. I know I can do this:

?- is_classroom_occupied(mon, 8, 8_348),!.

or this to make the program work.

?- once(is_classroom_occupied(mon, 8, 8_348)).

I am writing my rules on notepad++ and then using consult on prolog to use the file that has all my facts and rules. I do not want to use "once" or the cut operator on prolog, I want to somehow implement it while creating the rule on notepad++.

Upvotes: 0

Views: 2361

Answers (1)

Regis Alenda
Regis Alenda

Reputation: 499

I would suggest to wrap is_classroom_occupied into another predicate who will perform check whether a classroom is occupied and will succeed at most once.

check_classroom_occupied(Day, Timeslot, Location) :- 
    is_classroom_occupied(Day, Timeslot, Location), !.

Now when you consult the file, you can use check_classroom_occupied instead of is_classroom_occupied.

It may be possible to cleverly rewrite is_classroom_occupied so that it takes advantage of clause indexing to succeed at most once, but given your example data this seems to be difficult...

Also, as noted by Willem Van Onsem, your last clause does not seem to make sense and should probably be deleted.

Upvotes: 0

Related Questions