Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: st: Should be simple yet ... how to write a function?


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   RE: st: Should be simple yet ... how to write a function?
Date   Wed, 18 Feb 2009 12:08:56 -0000

It's entirely separate of the main point, but Maarten's example contains a bug. The body of the program should be 

c_local `1' = (`2')^2

For further explanation, see 

FAQ     . . . . . . . . . . . . . .  The use of macros with the power operator
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W. Gould
        12/99   I coded `a'^2 and got the wrong sign. Why?
                <http://www.stata.com/support/faqs/lang/macpow.html>

Nick 
[email protected] 

Maarten buis

--- On Wed, 18/2/09, Fabrice <[email protected]> wrote:
> how does one write a *function*, i.e. a program that returns
> a value, and that can be called like local y = fct(x), where
> x and y are numbers or strings. <snip>
> FYI, I know about r-type vs. e-type program, and know how to
> store results to return to main program.

Short answer: you can't.

Longer answer:

You can leave a local behind using the not documented
-c_local- command, so in the example below the program 
square leaves behind a local called foo

*------------ begin example ---------
capture program drop square
program define square
	c_local `1' = `2'^2
end
square foo 2
di `foo'
*------------ end example -----------

You can make a function like program that works with
the -egen- command, but this will only make variables.
To do so call your program _g<whatever>.ado, to create
the whatever "function". You can look at 
-viewsource _gcount.ado- to see an example of such a
program. Alternatively you can make a function in Mata,
but that will only function as a function within Mata.


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index