c++lazy-evaluationxtensor

lazy-evaluation in Xtensor


In the following function using xtensor, I was expecting the compiler to express the computation graph to auto z = 3.0 * u + 100 * xt::cos(u); and evaluate the result at xt::xtensor_fixed<T, xt::xshape<nn>> out = z; when assigning the expression to an exact tensor.

template<typename T, size_t nn>
T func_cos(xt::xtensor_fixed<T, xt::xshape<nn>> &u) {

    auto z = 3.0 * u;
    for (auto k = 0; k < 100; ++k){
        z += xt::cos(u);
    }
    xt::xtensor_fixed<T, xt::xshape<nn>> out = z;
    return out(0);
}

However, I got an error

views_xtensor.cpp:76:11: error: no viable overloaded '+='
        z += xt::cos(u);
[....]

Did I use auto in an wrong way? How could I use lazy evaluation in a for-loop?

Thank you for your help!


Solution

  • When you write

    auto z = 3.0 * u
    

    The type of z encodes the operation, it is something like

    xfunction<multiplies, scalar<double>, xtensor_fixed>
    

    This class does not hold any value, so it is not possible to assign it anything (even if it is a computed assignment). Now even if iw was possible, consider the following expression

    auto y = z + xt::cos(u);
    

    The type of this expression is something like

    xfunction<plus, type(z), xfunction<cos, xtensor_fixed>>
    

    So when you write

    z += xt::cos(u); // equivalent to z = z + xt::cos(u);
    

    You try to assign z something of a completely different type.

    Lazy evaluation cannot be used in for loops for these reasons.