Functions are special modules that return a single value. To write a function module, include a RETURN statement that specifies the value to return. The RETURN statement is necessary for a module to be a function. You can use a function module in an assignment statement, as you would a built-in function.
The symbol-table logic described in the preceding section also applies to function modules. In the following function module,
the value of c
in the local symbol table is assigned to the symbol z
at main scope:
proc iml; a = 10; b = 20; c = 30; start Mod3(x,y); c = 2#x + y; return (c); /* return function value */ finish Mod3; z = Mod3(a,b); /* call function */ print a b c z;
Notice the following about this example:
a
is still 10 and b
is still 20.
c
is still 30. The symbol c
in the global table has no connection with the symbol c
in the local table.
z
assigned the value 40, which is the value returned by the module.
Again notice that, inside the module, the symbols a
, b
, and z
do not exist. Outside the module, the symbols x
and y
do not exist.
In the next example, you define your own function module, Add, which adds its two arguments:
proc iml; start Add(x,y); sum = x+y; return(sum); finish; a = {9 2, 5 7}; b = {1 6, 8 10}; c = Add(a,b); print c;
Function modules can also be called as arguments to other modules or to built-in functions. For example, in the following statements, the Add module is called twice, and the results from those calls are used as arguments to call the Add module a third time:
d = Add(Add({1 2},{3 4}), Add({5 6}, {7 8})); print d;
Functions are resolved in the following order:
SAS/IML built-in functions
user-defined function modules
SAS DATA step functions
Because of this order of resolution, it is an error to try to define a function module that has the same name as a SAS/IML built-in function.