Skip to content

factor size zero tests into variadic function #589

@bob-carpenter

Description

@bob-carpenter

Summary:

There is code duplication in checking if any of the inputs to a probability funciton are size zero. These should all be replaceable by a single variadic C++11 function.

Description:

The non-variadic version for three arguments would replace

!(stan::length(y) && stan::length(alpha) && stan::length(beta))

with

size_zero(y, alpha, beta)

defined in the fixed size case by

template <typename T1, typename T2, typename T3>
bool size_zero(const T1& x1, const T2& x2, const T3& x3) {
  return !length(x1) || !length(x2) || !length(x3);
}

Distributing the negation through the conjunction leads to the simple recursive form for a variadic template:

template <typename T>
bool size_zero(T& x) {
  return !length(x);
}

template <typename T, typename ... Ts>
bool size_zero(T& x, Ts&&... xs) {
  return size_zero(x) || size_zero(std::forward<Ts>(xs)...);
}

I tested that the above works. You need the std::forward to "unpack" the parameter pack xs and std::forward with that whacky ... syntax to allow it to be passed to another argument. The const gets rolled into the T and Ts on the call.

This should be defined in the lowest typed prim/*/fun where length is available to be imported.

Current Version:

v2.16.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions