user1211185
user1211185

Reputation: 731

How to write IF ELSE conditions in Prolog

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.

Upvotes: 4

Views: 24976

Answers (1)

Rohit Sai Janga
Rohit Sai Janga

Reputation: 160

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
)

Upvotes: 6

Related Questions