Re: st: mata: evaluating strings and functions as arguments?

Matissa Hollister <m73hollis@yahoo.com> asked two Mata questions:

> 1) is there a way to get mata to evaluate the content of a string scalar, > e.g.: > > if I type: b="4+5" > > then I later type: b > it returns 4+5 > > is there a way that I can get it to evaluate b, i.e. return 9?

We need to write a function. Let's write

real scalar expandit(string scalar s)

that given a string (such as "4+5") returns the numeric evaluation (say 9):

real scalar expandit(string scalar s) { stata("scalar XYZZY = " + s) return(st_numscalar("XYZZY")) }

Do you see what I did. Pretend x contained "4+5". I passed the string "scalar XYZZY = 4+5" to Stata for execution, and then returned the value of the numeric scalar.

With my new function -expandit()-, I can do exactly what Matisa wants, I merely code -expandit(b)-.

The function could be improved. As it stands right now, it uses a fixed name for the scalar, although an unlikely one, and it leaves the scalar behind. The improved verison of expandit() would read

real scalar expandit(string scalar s) { string scalar tname real scalar result

tname = st_tempname() stata("scalar " + tname + " = " + s) result = st_numscalar(tname)

stata("scalar drop " + tname)

return(result) }

Matissa's second question was

> 2) Is there an easy way to have a function be an argument for another > function? Basically, I'd like to define a function that allows for > different methods for calculating a value, so I'd like to be able to > specify as an argument for the function which calculation function to > use.

Type -help [m2] ftof- for the complete answer. You can pass functions to functions by coding an & in front of the function name:

myfunc(.., &mysub(), ...)

and then, inside the receiving function, you can execute it by including a * in front of the name with which it was received:

function myfunc(..., f, ...) { ... x = (*f)(argments) ... }

-- Bill wgould@stata.com * * For searches and help try: * http://www.stata.com/support/faqs/res/findit.html * http://www.stata.com/support/statalist/faq * http://www.ats.ucla.edu/stat/stata/

Tag: