14.03.2014 Views

Scripting Guide - SAS

Scripting Guide - SAS

Scripting Guide - SAS

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

216 Programming Methods Chapter 8<br />

Advanced Programming Concepts<br />

dt=new table(); // to get an empty data table<br />

if (nrow(CurrentDataTable())==0, throw("!Empty Data Table"));<br />

Functions<br />

JSL also has a function called Function to extend the macro concept with a local context arguments.<br />

Suppose that you want to create a function that takes the square root but tolerates negative arguments,<br />

returning zero rather than errors. You first specify the local arguments in a list with braces { } and then state<br />

the expression directly. You do not need to enclose the expression in Expr because Function stores it as an<br />

expression implicitly.<br />

myRoot = function({x},if(x>0,sqrt(x),0));<br />

a = myRoot(4); // result in a is 2<br />

b = myRoot(-1); // result in b is 0<br />

Functions are stored in globals, the same as values. This means that you cannot have both a root function<br />

and a root value. It also means that you can redefine a function anytime except when you are inside the<br />

function itself.<br />

When a function is called, its arguments are evaluated and given to the local variables specified in the list<br />

forming the first argument. Then the body of the function, the second argument, is evaluated.<br />

The values of the arguments are for the temporary use of the function. When the function is exited, the<br />

values are discarded. The only value returned is the return value. If you want to return several values, then<br />

return a list instead of a single value.<br />

In defined functions, the stored function is not accessible directly, even by the Name Expr command. If you<br />

need to access the function expression in your script, you have to create the function within an expr()<br />

clause. For example,<br />

makeFunction = expr(myRoot=function({x}, if (x>0, sqrt(x), 0)));<br />

d=substitute(<br />

NameExpr(MakeFunction),<br />

expr(x), expr(y)<br />

);<br />

show(d);<br />

makeFunction;<br />

Local Symbols<br />

You can declare variables as local to a function so that they do not affect the global symbol space. This is<br />

particularly useful for recursive functions, which need to keep separate the values of the local variables at<br />

each level of function call evaluation.<br />

As shown above, a function definition looks as follows.<br />

functionName=Function({arg1, ...}, body);<br />

You can also have the function definition default all the unscoped names to be local.<br />

functionName=Function({arg1, ...}, {Default Local}, body);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!