Page 1 of 1

While Loop and for

Posted: 20 Feb 2014 20:19
by Eftychios
Hello,

I try to write in Prolog a while loop like the following:

while (count != 0){
count = count - 1;
}

or how can i make a for loop with pace i = i + 1 ????

I'm looking forward to receiving your reply

Thank you in advance

Posted: 21 Feb 2014 7:42
by Tonton Luc
Hi,

:idea: Maybe this following code can help you :

Code: Select all

    foreach Cpt = std::downTo(50,0) do         stdio::writef("Cpt = %\n",Cpt)     end foreach,

Posted: 21 Feb 2014 8:44
by Eftychios
Goodmorning,

Thank you very much, this works fine. Is there anything also for a while loop ??

Eftychios

Posted: 21 Feb 2014 9:48
by Thomas Linder Puls
Prolog does not have that kind of looping at all. In Prolog you either use recursion or backtracking. The foreach construction uses backtracking to do something that looks and feels like a loop.

Recursion is the fundamental iteration technique used in Prolog. Sometimes you use backtracking-loops but that should be a secondary alternative.

In imperative languages (like C/C++) you would very often traverse/iterate through an array by iterating through the index. You should never apply that technique in Prolog. In Prolog the array would (often/naturally) be a list and you would iterate through it using recursion:

Code: Select all

predicates     sum : (integer* L) -> integer Sum. clauses     sum([]) = 0.     sum([H|T]) = H+ sum(T).
The sum of ther elements in the empty list is (by natural definition) zero. The sum of the elements in a list with head H and tail T is H plus the sum of the elements in the tail, i.e. H + sum(T).

The algorithm is recursive (sum is calculated by calling itself).