if in prolog?
if in prolog?
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. Thats 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
).
A standard prolog predicate will do this.
isfive(5).
will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use =
isNotEqual(A,B):- A=B.
Technically it is does not unify, but it is similar to not equal.
Learn Prolog Now is a good website for learning prolog.
Edit:
To add another example.
isEqual(A,A).
if in prolog?
Prolog predicates unify –
So, in an imperative langauge Id write
function bazoo(integer foo)
{
if(foo == 5)
doSomething();
else
doSomeOtherThing();
}
In Prolog Id write
bazoo(5) :- doSomething.
bazoo(Foo) :- Foo =/= 5, doSomeOtherThing.
which, when you understand both styles, is actually a lot clearer.
Im bazoo for the special case when foo is 5
Im bazoo for the normal case when foo isnt 5