If Else in Prolog

Branching with if and else in Prolog is implemented using pattern matching and the -> (if-then-else) operator.

main :-
    % Here's a basic example.
    (7 mod 2 =:= 0 ->
        writeln('7 is even')
    ;
        writeln('7 is odd')
    ),

    % You can have an `if` statement without an else.
    (8 mod 4 =:= 0 ->
        writeln('8 is divisible by 4')
    ; true),

    % Logical operators like `,` (AND) and `;` (OR) are often useful in conditions.
    (8 mod 2 =:= 0 ; 7 mod 2 =:= 0 ->
        writeln('either 8 or 7 are even')
    ; true),

    % In Prolog, we can use pattern matching for conditional logic.
    % This is similar to a statement preceding conditionals in other languages.
    check_num(9).

check_num(Num) :-
    (Num < 0 ->
        format('~w is negative~n', [Num])
    ; Num < 10 ->
        format('~w has 1 digit~n', [Num])
    ;
        format('~w has multiple digits~n', [Num])
    ).

To run this program:

?- main.
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
true.

Note that in Prolog, we use pattern matching and the -> operator for conditional logic. The structure is (Condition -> ThenClause ; ElseClause). Also, Prolog uses , for logical AND and ; for logical OR.

There is no direct equivalent to a ternary operator in Prolog, as conditional logic is typically handled through pattern matching and the -> operator.

Markdown formatting has been applied to the code and explanations, making it suitable for Hugo. The structure and explanations have been maintained while adapting to Prolog’s syntax and conventions.