Skip to content

Commit faffb4a

Browse files
authored
Merge pull request #2835 from stan-dev/feature/2709-print-tuples
Allow printing of tuples
2 parents 224e581 + ba633b0 commit faffb4a

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

stan/math/prim/fun/stan_print.hpp

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33

44
#include <stan/math/prim/meta.hpp>
55
#include <stan/math/prim/fun/Eigen.hpp>
6+
#include <stan/math/prim/functor/for_each.hpp>
67
#include <vector>
78

89
namespace stan {
910
namespace math {
1011
// prints used in generator for print() statements in modeling language
1112

12-
template <typename T, require_not_container_t<T>* = nullptr>
13+
template <typename T, require_not_container_t<T>* = nullptr,
14+
require_not_tuple_t<T>* = nullptr>
1315
void stan_print(std::ostream* o, const T& x) {
1416
*o << x;
1517
}
@@ -50,8 +52,8 @@ void stan_print(std::ostream* o, const EigMat& x) {
5052
*o << ']';
5153
}
5254

53-
template <typename T>
54-
void stan_print(std::ostream* o, const std::vector<T>& x) {
55+
template <typename T, require_std_vector_t<T>* = nullptr>
56+
void stan_print(std::ostream* o, const T& x) {
5557
*o << '[';
5658
for (size_t i = 0; i < x.size(); ++i) {
5759
if (i > 0) {
@@ -62,6 +64,23 @@ void stan_print(std::ostream* o, const std::vector<T>& x) {
6264
*o << ']';
6365
}
6466

67+
template <typename T, require_tuple_t<T>* = nullptr>
68+
void stan_print(std::ostream* o, const T& x) {
69+
*o << '(';
70+
constexpr auto tuple_size = std::tuple_size<std::decay_t<T>>::value;
71+
size_t i = 0;
72+
stan::math::for_each(
73+
[&i, o](auto&& elt) {
74+
if (i > 0) {
75+
*o << ',';
76+
}
77+
stan_print(o, elt);
78+
i++;
79+
},
80+
x);
81+
*o << ')';
82+
}
83+
6584
} // namespace math
6685
} // namespace stan
6786
#endif

test/unit/math/prim/fun/stan_print_test.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ TEST(MathPrim, basic_print) {
99
Eigen::MatrixXd m = Eigen::MatrixXd::Ones(1, 1);
1010
std::vector<double> a(1, 1);
1111

12+
std::tuple<Eigen::VectorXd, int, std::vector<double>> tup(v, i, a);
13+
1214
{
1315
std::stringstream s;
1416
stan::math::stan_print(&s, i);
@@ -44,6 +46,12 @@ TEST(MathPrim, basic_print) {
4446
stan::math::stan_print(&s, a);
4547
EXPECT_TRUE(s.str().find("[1]") != std::string::npos);
4648
}
49+
50+
{
51+
std::stringstream s;
52+
stan::math::stan_print(&s, tup);
53+
EXPECT_TRUE(s.str().find("([1],1,[1])") != std::string::npos);
54+
}
4755
}
4856

4957
TEST(MathPrim, basic_expressions) {

0 commit comments

Comments
 (0)