This is an old version, view current version.

6.11 Higher-Order Functions

There are several expression constructions in Stan that act as higher-order functions.4

The higher-order functions and the signature of their argument functions are listed in the higher-order functions table.

Higher-order Functions Table. Higher-order functions in Stan with their argument function types. The first group of arguments has no restrictions. The second group of arguments, consisting of a real and integer array in all cases, must be expressions involving only data and literals.

function unrestricted args data args return type
algebra_solver vector, vector real[], int[] vector
integrate_1d, real, real, real[] real[], int[] real
integrate_ode_X, real, real[], real[] real[], int[] real[]
map_rect vector, vector real[], int[] vector

For example, the rectangular mapping function might be used in the following way to compute the log likelihood of a hierarchical model.

functions {
  vector foo_ll(vector phi, vector theta, real[] x_r, int[] x_i) {
    ...
...
vector[11] phi;
vector[2] thetas[N];
real x_rs[N, 5];
real x_is[N, 0];
...
target += sum(map_rect(foo_ll, phi, thetas, x_rs, x_is));

The function argument is foo, the name of the user-defined function; as shown in the higher-order functions table, foo takes two vectors, a real array, and an integer array as arguments and returns a vector.

Functions Passed by Reference

The function argument to higher-order functions is always passed as the first argument. This function argument must be provided as the name of a user-defined or built-in function. No quotes are necessary.

Data-Restricted Arguments

Some of the arguments to higher-order functions are restricted to data. This means they must be expressions containing only data variables, transformed data variables, or literals; the may contain arbitrary functions applied to data variables or literals, but must not contain parameters, transformed parameters, or local variables from any block other than transformed data.

For user-defined functions the qualifier data may be prepended to the type to restrict the argument to data-only variables.


  1. Internally, they are implemented as their own expression types because Stan doesn’t have object-level functional types (yet).↩︎