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.

194 Programming Methods Chapter 8<br />

Lists and Expressions<br />

Substituting<br />

Substitute and Substitute Into merit further discussion. Both find all matches to a pattern in a list<br />

(or expression) and replace them with another expression. Each pattern must be a name. The arguments are<br />

evaluated before they are applied, so most of the time you must quote them with an Expr function.<br />

Substitute({a,b,c}, expr(a), 23); // produces {23,b,c}<br />

Substitute(expr(sine(x)),expr(x),expr(y)); // produces sine(y)<br />

To delay evaluating an argument, use NameExpr instead of Expr:<br />

a={quick,brown,fox,jumped,over,lazy,dogs};<br />

b=Substitute(a,expr(dogs),expr(cat));<br />

canine=expr(dogs);equine=expr(horse);<br />

c=Substitute(a,nameexpr(canine),nameexpr(equine)); show(a,b,c);<br />

a = {quick,brown,fox,jumped,over,lazy,dogs}<br />

b = {quick,brown,fox,jumped,over,lazy,cat}<br />

c = {quick,brown,fox,jumped,over,lazy,horse}<br />

Substitute Into does the same work, in place:<br />

Substitute Into(a,expr(dogs),expr(horse));<br />

You can list multiple pattern and replacement arguments to do more than one replacement in a single step:<br />

d=Substitute(a,<br />

nameexpr(quick),nameexpr(fast),<br />

nameexpr(brown),nameexpr(black),<br />

nameexpr(fox),nameexpr(wolf)<br />

);<br />

{fast,black,wolf,jumped,over,lazy,dogs}<br />

Note that substitutions are done repeatedly over multiple instances of the expression pattern. For example:<br />

Substitute(expr(a+a), expr(a), expr(aaa));<br />

results in:<br />

aaa + aaa<br />

Manipulating expressions<br />

The operators for manipulating lists can also operate on most expressions. Be sure to quote the expression<br />

with Expr. For example:<br />

Remove(Expr(A+B+C+D),2); // results in the expression A+C+D<br />

b=Substitute(expr(log(2)^2/2), 2, 3); // results in the expression Log(3)^3/3<br />

As with lists, remember that the first argument for in-place operators must be an L-value. An L-value is an<br />

entity such as a global variable whose value can be set. In-place operators are those that operate on lists or<br />

expressions directly. They have From or Into in their names (for example, Remove From and Insert<br />

Into). They do not return a result; you have to show the expression to see the result.<br />

polynomial=expr(a*x^2 + b*x + c);<br />

insertinto(polynomial,expr(d*x^3),1);

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

Saved successfully!

Ooh no, something went wrong!