Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'if' in prolog?

Is there a way to do an if in prolog, e.g. if a variable is 0, then to do some actions (write text to the terminal). An else isn't even needed, but I can't find any documentation of if.

like image 321
jreid9001 Avatar asked May 17 '10 12:05

jreid9001


People also ask

Does Prolog have if?

Prolog has a builtin if-then-else syntax.

How do you write an if else condition in Prolog?

Program. % If-Then-Else statement gt(X,Y) :- X >= Y,write('X is greater or equal'). gt(X,Y) :- X < Y,write('X is smaller'). % If-Elif-Else statement gte(X,Y) :- X > Y,write('X is greater').

What does =:= mean in Prolog?

=:= expression is meaning of exactly equal. such as in JavaScript you can use === to also see if the type of the variables are same. Basically it's same logic but =:= is used in functional languages as Prolog, Erlang.


1 Answers

Yes, there is such a control construct in ISO Prolog, called ->. You use it like this:

( condition -> then_clause ; else_clause ) 

Here is an example that uses a chain of else-if-clauses:

(   X < 0 ->     writeln('X is negative.  That's weird!  Failing now.'),     fail ;   X =:= 0 ->     writeln('X is zero.') ;   writeln('X is positive.') ) 

Note that if you omit the else-clause, the condition failing will mean that the whole if-statement will fail. Therefore, I recommend always including the else-clause (even if it is just true).

like image 92
Matthias Benkard Avatar answered Sep 22 '22 22:09

Matthias Benkard