User-defined function: put default argument

The idea is to construct a function that takes the row position and column position of a given (or several) element in a matrix and return the position of these elements if this matrix is transformed into a vector.
For example, assume that we have a matrix 3 by 4. If I give the row position “1” and column position “2”, it should return “4”.
Other examples:
1,1->1
2,1->2
3,1->3
1,2->4
2,2->5
etc.

It could also take int arrays:
{1,2},{1,2}->{1,2,4,5}
{1},{2,4}->{4,11}.

This is possible by adding the following function (in the function block):

functions {
int[] ind(int[] comp, int[] age_sex){ //get the vector index for a given compartment index and age_sex index
  int s1=size(comp);
  int s2=size(age_sex);
  int v[s1*s2];
  int index=1;
  for(i in comp){
    for(j in age_sex){
      v[index]=i+(j-1)*3;
      index=index+1;
    }
  }
  return v;
}

However, this function doesn’t handle missing values (there is no default argument). For example, I want that :
ind({1,2},) → {1,2,4,5,7,8,10,11}
ind(,{1}) → {1,2,3}

I would also like to to be able to drop the “{}” when only one element is given as in the last example.

So three short questions:

  1. How to define default argument when it is missing?
  2. Is it possible to define several signatures for an argument (e.g. int and int[]) so that I don’t have to add the “{}” when I use only one element?
  3. Doesn’t such a function already exist? My problem seems simple and I’m wondering whether such a function hasn’t been defined before.

Neither are possible in Stan at the moment. The second is called “overloading” and is something I plan to work on soon, but I don’t think we have any proposals for how to do default arguments.

Usually in languages like python this is tied to the idea of keyword arguments, so you would write ind(age_sex={1}) for example. I’m not sure how useful they would be in general

1 Like