up previous next
1.1.8 Tutorial: defining new functions
To define a new function in CoCoA use the command define .

When defining a new function you must pick a new name for the function, and state what arguments/parameters it expects. The parameters and variables used inside the function are different from any variables outside it (even if the names look the same).

Strictly there is a difference between "functions" and "procedures": the former always return values, while the latter never return values. In CoCoA there is hardly any distinction: the only difference is the use of the return command inside the fn-proc.

  /**/ -- Define new fn "SimpleFn" with just 1 parameter:
  /**/ define SimpleFn(N) return N^2+1; enddefine;
  /**/ SimpleFn(3);

  /**/ define OneStep(N)
  /**/   if IsEven(N) then return N/2;
  /**/   else return 3*N+1;
  /**/   endif;
  /**/ enddefine;
  /**/ OneStep(5);

  /**/ define MaxAbs(X, Y)  -->  2 parameters
  /**/   return max(abs(X), abs(Y));
  /**/ enddefine;
  /**/ MaxAbs(2, -3);

  /**/ -- Next defn is a "procedure" (returns no value)
  /**/ define CheckIsPositive(X)
  /**/   if X <= 0 then println "NOT POSITIVE"; endif
  /**/ enddefine