15 março 2017

Listing items of a list

Int his case, when it is necessary to just list items of a list, a loop and the nth function may be used. To control the loop a variable can be started with 0 (zero) incrementing by 1 until the size of the list minus 1. To get the length of the list, the internal function length can be used.
The following code is showing a simple example with a list o products declared as a belief. In the start goal a variable "Count" in the first iteration is unified with 0 and compared, being less than "ListLength" (in this example is number 3). After this, the function "nth" returns the nth item List, first 0, than 1 and finally 2 in the last iteration. nth function unifies the nth item in the variable List. Finally the code just print the result and increment Count.

products(["Banana", "Apple", "Pineapple"]).
!start.

+!start : products(List) <-
 .length(List,ListLength);
-+listSize(0);
while(listSize(Count) & Count < ListLength)
{        
.nth(Count,List,Item);
.print("Product(",Count,"): ",Item);
-+listSize(Count+1);
 }.