So basically I am trying to simulate some C code in Prolog.
It is easy to simulate while loop in Prolog Here is the case:
C code:
int a = 1;
The most obvious way to do an infinite loop in Prolog is with repeat/0
, and it looks like this:
while(1)
do_something();
becomes
repeat,
do_something.
The real problem then becomes that there's no obvious analog to goto
or break
in Prolog. So I would be inclined to look for a pattern like this:
while(1) {
if (test)
break;
do_something();
}
and convert it to Prolog like this:
loop_entry :-
test,
do_something,
loop_entry.
You will of course need to add your local variables as parameters to loop_entry/0
and implement test
, but this way when test
fails the loop will end naturally.
Following your example with N and A leads to this kind of thing:
loop_entry(N, A) :-
N > 0,
succ(N0, N),
succ(A, A1),
loop_entry(N0, A1).
The "test" in this case is simply N > 0
. If it isn't true, the predicate will simply fail and you can go on with life the Prolog way.
Edit #2. If you want the results (N and A) then add additional parameters for the values you want to return and add one more clause:
loop_entry(N, A, ResultN, ResultA) :-
N > 0, !,
succ(N0, N),
succ(A, A1),
loop_entry(N0, A1, ResultN, ResultA).
loop_entry(N, A, N, A).
You can either add a cut after the condition or put the inverse condition in this new clause.