Discussions related to Visual Prolog
Eftychios
Posts: 14
Joined: 19 Feb 2014 10:37

While Loop and for

Unread post 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
User avatar
Tonton Luc
VIP Member
Posts: 204
Joined: 16 Oct 2001 23:01

Unread post 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,
Eftychios
Posts: 14
Joined: 19 Feb 2014 10:37

Unread post by Eftychios »

Goodmorning,

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

Eftychios
User avatar
Thomas Linder Puls
VIP Member
Posts: 1401
Joined: 28 Feb 2000 0:01

Unread post 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).
Regards Thomas Linder Puls
PDC
Post Reply