4

I am a C# guy and very new to prolog. I need to write a prolog program for the following scenario. Can anyone please help to achieve it.

Two person share a chest of drawers. Chest have 4 drawers and Drawer 1 and 2 belongs to Person1 and Drawer 3 and 4 belongs to Person2.

They keep their Mobile phone, wallets and books in drawers. Person2 lost his phone in drawers. He checked in drawer 3 and 4 which belongs to him but could not find his phone. Then he checked drawers 1 and 2 and found it in drawer 2. I need to write prolog code for this scenario.

person(person1).
person(person2).

drawers(drawer1).
drawers(drawer2).
drawers(drawer3).
drawers(drawer4).

belongs_to(drawer1, person1).
belongs_to(drawer2, person1).
belongs_to(drawer3, person2).
belongs_to(drawer4, person2).

item(phone2).

phone_in(drawer).
phone_in(drawer2).

commands to run and their results

?- phone_in(drawer4).
false.

?- phone_in(drawer3).
false.

?- phone_in(drawer1).
false.

?- phone_in(drawer2).
true.

I am trying to write a condition as following.

?- phone_in(drawer2).
true.

Want to run condition based on the result of above query (true/false).

if(false)
    write("phone not found!");
else if(true)
    write("please found in your search area");

Please suggest me to improve my code.

false
  • 10,264
  • 13
  • 101
  • 209
user1211185
  • 731
  • 3
  • 12
  • 27
  • See [here](http://www.swi-prolog.org/pldoc/man?section=control) how to write if-then-else in Prolog. – Tudor Berariu Jan 08 '15 at 16:00
  • duplicate of https://stackoverflow.com/questions/14945623/prolog-if-else-statement-with-or-condition ? – Tilman Hausherr Jan 08 '15 at 16:00
  • If you want feedback on your working code, try posting a question on [codereview](http://codereview.stackexchange.com/questions/tagged/prolog). – Tudor Berariu Jan 08 '15 at 16:12
  • see [this question](http://stackoverflow.com/q/2849045/772868) – false Jan 08 '15 at 16:17
  • Why do you want to state that the phone is not found, if it is in drawer4? It seems your logic needs first some update. – false Jan 08 '15 at 16:19
  • @TilmanHausherr suggested answer is not helping me as I want to run condition based on the return of my query. – user1211185 Jan 08 '15 at 16:42
  • Not clear what you're after, but here's how if-then-else works: `find_phone(Loc) :- (phone_in(Loc) -> write('Found it!') ; write('Sorry, not there')), nl.` – lurker Jan 09 '15 at 03:21

1 Answers1

5

Syntax is like this

( condition -> then_clause ; else_clause )

It may be written in this fashion

( phone_in(drawer2) =:= true ->  
  write('phone found in your search area'),
  fail
  ; phone_in(drawer2) =\= false -> 
  ; write('phone not found!'),nl
)
zx485
  • 28,498
  • 28
  • 50
  • 59
Rohit Sai Janga
  • 150
  • 2
  • 6