This is an old version, view current version.

9.5 Function Bodies

The body of a function is between an open curly brace ({) and close curly brace (}). The body may contain local variable declarations at the top of the function body’s block and these scope the same way as local variables used in any other statement block.

The only restrictions on statements in function bodies are external, and determine whether the log probability accumulator or random number generators are available; see the rest of this section for details.

Random Number Generating Functions

Functions that call random number generating functions in their bodies must have a name that ends in _rng; attempts to use random-number generators in other functions lead to a compile-time error.

Like other random number generating functions, user-defined functions with names that end in _rng may be used only in the generated quantities block and transformed data block, or within the bodies of user-defined functions ending in _rng. An attempt to use such a function elsewhere results in a compile-time error.

Log Probability Access in Functions

Functions that include sampling statements or log probability increment statements must have a name that ends in _lp. Attempts to use sampling statements or increment log probability statements in other functions lead to a compile-time error.

Like the target log density increment statement and sampling statements, user-defined functions with names that end in _lp may only be used in blocks where the log probability accumulator is accessible, namely the transformed parameters and model blocks. An attempt to use such a function elsewhere results in a compile-time error.

Defining Probability Functions for Sampling Statements

Functions whose names end in _lpdf and _lpmf (density and mass functions) can be used as probability functions in sampling statements. As with the built-in functions, the first argument will appear on the left of the sampling statement operator (~) in the sampling statement and the other arguments follow. For example, suppose a function returning the log of the density of y given parameter theta allows the use of the sampling statement is defined as follows.

real foo_lpdf(real y, vector theta) { ... }

Note that for function definitions, the comma is used rather than the vertical bar. Then the shorthand

z ~ foo(phi);

will have exactly the same effect

target += foo_lpdf(z | phi);

Unlike built-in probability functions, user-defined probability functions like the example foo above will not automatically drop constant terms.

The same syntax and shorthand works for log probability mass functions with suffixes _lpmf.

A function that is going to be accessed as distributions must return the log of the density or mass function it defines.