4 Declarations — Declarations and types
and it would have worked just fine. So why include the declarations?
1. By including the outside declaration, we announced to other programs what to expect. They
can depend on swaprows() returning a real matrix because, when swaprows() is done,
Mata will verify that the function really is returning a real matrix and, if it is not, abort
execution.
Without the outside declaration, anything goes. Our function could return a real scalar in
one case, a complex row vector in another, and nothing at all in yet another case.
Including the outside declaration makes debugging easier.
2. By including the argument declaration, we announced to other programmers what they are
expected to pass to our function. We have made it easier to understand our function.
We have also told Mata what to expect and, if some other program attempts to use our
function incorrectly, Mata will stop execution.
Just as in (1), we have made debugging easier.
3. By including the inside declaration, we have told Mata what variables we will need and how
we will be using them. Mata can do two things with that information: first, it can make
sure that we are using the variables correctly (making debugging easier again), and second,
Mata can produce more efficient code (making our function run faster).
Interactively, we admit that we sometimes define functions without declarations. For more careful
work, however, we include them.
Types, element types, and organizational types
When you use Mata interactively, you just willy-nilly create new variables:
: n = 2
: A = (1,2 \ 3,4)
: z = (sqrt(-4+0i), sqrt(4))
When you create a variable, you may not think about the type, but Mata does. n above is, to Mata,
a real scalar. A is a real matrix. z is a complex row vector.
Mata thinks of the type of a variable as having two parts:
1. the type of the elements the variable contains (such as real or complex) and
2. how those elements are organized (such as a row vector or a matrix).
We call those two types the eltype—element type—and orgtype—organizational type. The eltypes and
orgtypes are
eltype orgtype
transmorphic matrix
numeric vector
real rowvector
complex colvector
string scalar
pointer
You may choose one of each and so describe all the types Mata understands.