I need to define a matrix of int as a type. A column or a row of a matrix represent a city, an element in a matrix represent the distance between the city of row and the city of the column. The dimension of the matrix may change (we may add or remove cities), but it is always quite small.
I hesitate among int array array, int list list and a type with map which is defined as follows:
module MatOrd = struct
type t = string * string
let compare ((a, b): string * string) ((c, d) : string * string) =
if Pervasives.compare a c <> 0
then Pervasives.compare a c
else Pervasives.compare b d
end
module MatMap = Map.Make(MatOrd)
Then int MatMap.t could represent a matrix of int. An advantage of this definition is I can directly write the name of a city as a coordinate of the matrix. Wherease for int array array and int list list, it seems that I have to memorize the signification of the coordinates by heart…
Besides, is it true that we can’t do pattern-matching with an array? For instance, can’t we write:
match a_array with
[| first_element; the_rest_elements |] -> ...
With the advantages and disadvantages that I mentioned or not, which type do you suggest?
The applicability of this or that type really depends on which operations you mean to implement with it. What will you compute with your type ?
For example, you might want to avail yourself of matrix operations implemented somewhere such as min-plus multiplication, which may help you with a shortest path problem. In that case, it makes sense to use matrices, and have a separate function
string -> intthat translates from city name to matrix coordinates. On the other hand, if you just want a datastore on which computation will be scarce, aMaptype such as the one above might make better sense.It’s hard to give very insightful answers without knowing what you want to compute, but as for your proposals:
int list listhas a limited utilityif you make two-dimensional arrays, beware arrays are mutable references and that affectation is treated accordingly, so that after the following:
a.(0)equals42.The language has an eager evaluation strategy so that another caveat is that you shouldn’t create an array the following way:
The inner
makecall gets evaluated first, and the same reference is shared by the threelines of your outer array. See the FAQ on how to create matrices.
And by the way, you can do pattern-matching on arrays (the relevant manual section shows the pattern at the bottom of the page), but you have to respect the dimension of your array when placing pattern variables. Thankfully you can use
_, and as you said the dimension of your array is quite small.