Hi Stan Developers,

I would like add to this discussion from my own experience. Information on Stan is too scattered, often not clear, and sometimes even conflicting. In the post Multivariate Function with Known Gradients - RStan I was asking for help to implement the a simple function that is callable from a Stan program and uses pre-calculated gradients. I have tried to follow the approach in https://github.com/stan-dev/math/wiki/Adding-a-new-function-with-known-gradients to add my function, but without success. Additionally, I have tried to write my function in the same way as the `log_determinant`

in the Stan Math Library Reference:

```
namespace stan {
namespace math {
inline var vecToDoubleTwo(const Eigen::Matrix<var, Eigen::Dynamic, 1>& m) {
using Eigen::Matrix;
Matrix<double, Eigen::Dynamic, 1> m_d(m.rows());
for (int i = 0; i < m.size(); ++i)
m_d(i) = m(i).val();
double val = 0;
for (int i=0; i<m.size(); ++i) val += m_d(i) * m_d(i);
vari** varis
= ChainableStack::memalloc_.alloc_array<vari*>(m.size());
for (int i = 0; i < m.size(); ++i)
varis[i] = m(i).vi_;
double* gradients
= ChainableStack::memalloc_.alloc_array<double>(m.size());
for (int i = 0; i < m.size(); ++i)
gradients[i] = 2 * m_d(i);
return var(new precomputed_gradients_vari(val, m.size(),
varis, gradients));
}
}
}
```

This was also without success.

In both occasions I could use the function from a C++ program with the intended interface of the Stan Math Library. However, as soon as the function should be called from a Stan program, there are issues with variable types. The function works and Stan can find it. There is no problem to print output with it, e.g.

```
print(vecToDoubleTwo(x));
```

but

```
target += vecToDoubleTwo(x);
```

results in an error message saying that a `var`

can’t be assign to a `double`

(according to the Stan Math Library Reference, a `var`

should never be assigned to `double`

). It works nevertheless for the `log_determinant`

and I can’t find the correct information to fill in the missing links on how to implement the function correctly.

I will appreciate any help.

Regards,

Jonas