If statement in prolog recursion

108 views Asked by At

I need to write this code in prolog:

void rec_k(int k,int i,int j) { 
    if (!(k<9)) return;
    if ((i <> j) and (i <> k) and (j <> k)) {
        writeln(100 * i + 10 * j + k);
    }
    rec_k(k+1,i,j); 
}

I tried this:

rec_k(K, I, J):-
    ((K >= 9) -> !;
        ((I <> J and I <> K and J <> K) -> write(100 * I + 10 * J + K);)
    ),
    rec_k(K+1,I,J).

Doesn't work, of course.

1

There are 1 answers

0
Duda On

Try this:

writeKIJ(K,I,J):-
    (   I \= J, 
        I \= K, 
        J \= K
    ->  E is 100 * I + 10 * J + K,
        write(E),
        write('\n')
    ;   true
    ).

rec_k(K, I, J):-
    (   K < 9
    ->  writeKIJ(K,I,J),
        KK is K+1,
        rec_k(KK,I,J)
    ;   true
    ).

The output of rec_k(0,2,3). is

?- rec_k(0,2,3).
230
231
234
235
236
237
238
true.

Please note: arithmetic terms can be calculated by using is. My solution introduces a helper predicate which does the output: once it has checked that I, J and K are different it will prevent backtracking (with a so called cut !), calcluates and prints the output. If I, J and K are not different it will just do nothing. The main predicate rec_k/3 needs to know when to stop (not K < 9). Otherwise it will call the write-predicate and call itself with an incremented K (KK).

It can be written without the helper predicate (return the same output):

rec_k(K, I, J):-
    (   K >= 9
    ->  true
    ;   (   I \= J, 
            I \= K, 
            J \= K
        ->  E is 100 * I + 10 * J + K,
            write(E),
            write('\n')
        ;   true
        ),
        KK is K+1,
        rec_k(KK,I,J)
    ).