| |
Count
The internal Derive function dim() is often used. This calculates the number
of elements in a vector.
Suppose we wish to count the number of occurrences of an element in a one-dimensional vector.
For example, consider the vector q:=[4,5,f,g,-12,f,f,1,5,-9,20],
then the letter f appears 3 times. One possible solution could be:
count(array,var,vect):=
Prog
vect := SELECT(k = var, k, array)
DIM(vect) |
This uses the Derive in-built function SELECT(u,k,v),
where u is the function being tested -
in the vector u, that the number of
occurrences = f that, is k=var.
Also, to make the function easier to read, the intermediary vect
is used. Hence,
count(q, f)=3
As a one-line entry into Derive, the above routine is typed: count(array,
var, vect) := PROG(vect := SELECT(k = var, k, array), DIM(vect))
Notice that we have not declared the variable k (used in the internal
function SELECT) as a local variable. One must never declare variables
used in internal functions such as VECTOR, SUM, PRODUCT, etc as local.
Doing this can cause problems if you try to use the variables elsewhere in the
program.
We will demonstrate this with a contrived example:
fee(z, k) :=
Prog
k := 5
VECTOR(k^2, k, 1, z) |
fee(3) = [25, 25, 25]
As we have declared k as a local variable and defined k to be 5 in
the program, then this value for k is passed into the vector command. However,
if we remove k from the function parameter list (i.e. make k global)
fee(z) :=
Prog
k := 5
VECTOR(k^2, k, 1, z) |
fee(3) = [1, 4, 9] then
the declaration of k within the program does not affect the role of the k variable
in the VECTOR command. We can in fact make a much more compact version of the
function, without the need for a PROG()
and local variable vect. count(array,
var,) :=DIM(SELECT(k = var, k, array))
|