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
- Tonton Luc
- VIP Member
- Posts: 204
- Joined: 16 Oct 2001 23:01
Hi,
Maybe this following code can help you :
Maybe this following code can help you :
Code: Select all
foreach Cpt = std::downTo(50,0) do
stdio::writef("Cpt = %\n",Cpt)
end foreach,
- Thomas Linder Puls
- VIP Member
- Posts: 1424
- Joined: 28 Feb 2000 0:01
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:
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).
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 algorithm is recursive (sum is calculated by calling itself).
Regards Thomas Linder Puls
PDC
PDC