# Re: st: [Mata] passing a function to mata

 From wgould@stata.com (William Gould, Stata) To statalist@hsphsun2.harvard.edu Subject Re: st: [Mata] passing a function to mata Date Thu, 25 Aug 2005 13:34:33 -0500

```Antoine Terracol <Antoine.Terracol@univ-paris1.fr> wants to pass
a function to Mata.

He imagines a function

real scalar gaussher(funct)
{
...
... calls funct(x) somehow
...
return(...)
}

where funct is the name of a function.

The way to proceed is

real scalar gaussher(pointer(function) funct)
{
...
... (*funct)(x) ...
...
return(...)
}

Although, if you prefer, we could omit the "pointer(function)" part
(declarations are always optimal), and then our code would read.

real scalar gaussher(funct)
{
...
... (*funct)(x) ...
...
return(...)
}

In any case, we might define the function

function xsquared (real x)
{
return(x:^2)
}

and then, to execute gaussher() using xquared(), we would type

: gaussher(&xsquared())

xsquared() is the function we are passing to guassher().  In our call,
we put an & in front of the function name, to say that we do not want
to execute the function xsquared(); we merely wish to pass its identity

In our gaussher() function, the corresponding argument we receive is
"pointer(function) funct".  That states that funct will be the address
of a function.  Asterisk is the operator that substitutes the thing
itself for an address, so we execute the function by coding coding
(*funct)(x).

Try the following example:

. mata
--------------------------------- mata (type end to exit) -----
: function gaussher(funct)
> {
>          return( (*funct)(2) )
> }

: function me(x) return(x+3)

: gaussher(&me())
5

: end
---------------------------------------------------------------

For more information, see -help m2_ftof- on-line, or [M-2] ftof in the
manual.

-- 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/
```