user4075334
user4075334

Reputation:

Use if else in Prolog

I want to implement something of this sort using if else in Prolog.Being from C++ background I am finding it hard to implement.How can I do it???

if(X!=4 || Y!=3)
  printf("1");
else if(A!=4 || Y=3 && Z==2)
  printf("2");

Upvotes: 0

Views: 4738

Answers (2)

Kijewski
Kijewski

Reputation: 26022

If-else in Prolog is simply

Condition → Then ; Else

resp.

  Condition1 → Then1
; Condition2 → Then2
; …
; Else

Your C code

if(X!=4 || Y!=3)
    printf("1");
else if(A!=4 || Y==3 && Z==2)
    printf("2");

would translate to

  (X \= 4; Y \= 3)       -> write('1')
; (A \= 4; Y = 3, Z = 2) -> write('2')
; true   % or drop this line, then it will raise a unification error

But be aware that you should use write/1 only in the outer loops, because the function is impure (the order of execution matters).

Probably you should write something like:

( (X \= 4; Y \= 3)       -> Message = '1'
; (A \= 4; Y = 3, Z = 2) -> Message = '2'),
write(Message).

Be aware that Prolog is a logical programming language. Ofttimes you will find that a verbatim translation from an imperative programming language is not the best solution.

As an example see a question I answered a few days ago: "Calculating whether number is prime in Prolog":

Imperative:

is_prime(A) :-
    A > 1,                 % Negative numbers, 0 and 1 are not prime.
    is_prime(A, 2).        % Begin iteration:

is_prime(A, B) :-          % Test if A divides by B without remainder
    B >= A                 % The limit was reached?
    ->  true               %     Then it's prime.
    ;   0 is A mod B       % B divides A without a remainder?
    ->  false              %     Then it's not prime.
    ;   C is B + 1,        % Otherwise: C is B + 1
        is_prime(A, C).    % Test if C divides A.

Logical:

is_prime(A) :-
    L is A - 1,            % L is floor(sqrt(A))  ← optimized upper bound
    \+ (between(2, L, X),  % Is there a number X between 2 and L
        0 is A mod X).     % that divides A without a remainder?

Which is easier to read?

Upvotes: 2

Shevliaskovic
Shevliaskovic

Reputation: 1564

Try this bit of code:

main:- (X\=4 ; Y\=3) -> write('1') ; 
       (A \=3 ; Y is 3 , Z is 2) -> write('2').

\= equals !=
; equals ||
, equals &&
is equals =, but you can also use = for this.
-> equals then

I added four read/1 to test the code:

main:- read(X),read(Y),read(A),read(Z),
       (X\=4 ; Y\=3) -> write('1') ; 
       (A \=3 ; Y is 3 , Z is 2) -> write('2').

and I get:

3 ?- main.
|: 4.
|: 3.
|: 2.
|: 2.
2
true

Second if works

 6 ?- main.
|: 3.
|: 6.
1
true.

First if works

Upvotes: 1

Related Questions