3
votes

I have just started prolog and was wondering if we can implement conditional statements like(if.else)in Prolog also and if so how?? Can someone implement this code in Prolog just for an example-

if(a==2)
 print("A is 2");
if(a==3)
 print("A is 3");
else
 print("HAhahahahaah");

Ok so I am doing this after Sergey Dymchenko answer.

Test(A) :-read(A),
 ( A =:= 2 ->
    write('A is 2')
 ;
    ( A =:= 3 ->
        write('A is 3')
    ;
        write('HAhahahahaah')
    )
 ).

This is giving right answer except this is displaying A = 2 also which I dont want(If I give input 2).

1
@david Sorry but I am facing difficulty understanding it.Can you or someone please post a code where this is implemented.it would be easier to understand with a code..user4067810
I don't speak prolog, but also look at Prolog, conditional clausesDavidPostill
After you updated the question with read(Term). f(Term)==f(2) :- write('Hello world!'). I see that my answer will not help you. Consider reading some introductory Prolog text like "Learn Prolog Now!" learnprolognow.org first.Sergii Dymchenko
@Sergey Yeah I am reading from the same book you suggested.Can you help me a bit in taking input,I think I am going wrong thereuser4067810

1 Answers

6
votes

One way to do it:

test(A) :-
    (   A =:= 2 ->
        write('A is 2')
    ;   A =:= 3 ->
        write('A is 3')
    ;   write('HAhahahahaah')
    ).

Another way to do it:

test(2) :-
    write('A is 2').
test(3) :-
    write('A is 3').
test(A) :-
    A \= 2, A \= 3,
    write('HAhahahahaah').

There are differences with these two codes, like choice points, behavior when A is not instantiated, and if A is treated as a number or not. But both will work the same way (except choice points left) and as expected with queries test(2)., test(3)., test(42).