TopLists of ListsDefining Matrix

Defining Matrix

Nothing stops us from defining lists of lists. To declare a list, each of whose elements is a list of int:

def twoDList: List<List<Number>> = list.empty<List<Number>>

def firstList: List<Number> = list.with<Number>(3,4,5)
def secondList: List<Number> = list.with<Number>(10,11,12,13)

twoDList.add(firstList)
twoDList.add(secondList)

print(twoDList)

Each element of twoDlist is a list of Numbers. The results of the above print statement is:

[[3, 4, 5], [10, 11, 12, 13]]

Of course we could also build this directly without starting with an empty list:

def otherTwoDList: List<List<Number>> = list.with<List<Number>>(firstList, secondList)

If it so happens that every list in twoDList has the same length, then it can be useful to think about this as a two-dimensional list, with the elements arranged in a two-dimensional table so that twoDlist.at(i).at(j) can be seen as the element in the ith row and jth column. For example here is the layout for a two-dimensional list a with 5 rows (numbered 1 to 5) and 3 columns:

1 2 3
1 a.at(1).at(1) a.at(1).at(2) a.at(1).at(3)
2 a.at(2).at(1) a.at(2).at(2) a.at(2).at(3)
3 a.at(3).at(1) a.at(3).at(2) a.at(3).at(3)
4 a.at(4).at(1) a.at(4).at(2) a.at(4).at(3)
5 a.at(5).at(1) a.at(5).at(2) a.at(5).at(3)

Viewed in this way, our two-dimensional list is a grid, much like a map or a spreadsheet. This is a natural way to store things like tables of data or matrices.

To make it easier to create and access elements of such a two-dimensional table we have created a class matrix generating objects of type Matrix. Matrix

We can create a two-dimensional table by providing the type of values, the number of rows and columns, and the default value with which to initialize all slots. Thus we can create the two-dimensional list above by writing:

   def a:Matrix<Number> = matrix.size<Number>(5,3) defaultValue (0)

Type Matrix<T> is defined as follows:

type Matrix<T> = {
  at(r: Number, c: Number) -> T 
  at(r: Number, c: Number) put (value:T) -> Done
}

Thus we can access and update values by providing the row and column and, when updating, the new value.


TopLists of ListsDefining Matrix