To loop through the elements of a list, the following code would work:
def main()
{
list = [1,2,3,4];
for(k in 0..3)
println(list.k);
}
This program will demonstrate some other features of lists in Salsa. Many times you will not know exactly how long the list will be. In general, it may be useful to find the length of the list. To do this, use the record operator, and use "n" as the record instead of an integer. However, you cannot use "for(k in 0..list.n)" as the loop, because list.n is not in the list, since the list elements range from 0 to list.n-1.
Since for(k in 0..list.n-1) is cumbersome, and you will frequently want to do loop over all elements of a list, there is another list construct you can use for this purpose. Instead of a range, supply a list. Then k will range over each element of the list. Therefore, the above program becomes:
def main()
{
list = [1,2,3,4];
for(k in list)
println(k);
}
Operators work differently with lists, and there are some operators which work only with lists. When adding or subtracting two lists, or multiplying or dividing a list with another type of object, the result is the same as if the list were a vector. Adding or subtracting another type of object to a list causes it to be added or subtracted from every element of the list. Multiplying two lists is the same as the inner, or dot product with vectors, unless the lists form two matricies of correct dimensions, in which case matrix multiplication is preformed. Dividing lists is the same as multiplying the first by the inverse norm of the second, unless the lists are matricies in which case matrix division is preformed.
Some operators are list-specific. The conj operator returns the conjunction of two lists (in the set theory sense of every element which is in at least one list). For this the lists must be sorted. Information concerning sorting lists will come in a later section. The disj operator returns the disjunction of two lists (in the set theory sense of every element present in both lists), and also only operates on sorted lists.
There are many other things you can do with lists, but they involve knowledge of functions, and so will be covered in a later section. The next section in the Tutorial covers functions.
Web page maintained by Jason Cohen