diff --git a/include/cenet/math/expr.hpp b/include/cenet/math/expr.hpp index 711ff10..5f431e7 100644 --- a/include/cenet/math/expr.hpp +++ b/include/cenet/math/expr.hpp @@ -13,6 +13,9 @@ namespace math { struct expression_tag {}; +template +struct unary_expression; + template struct binary_expression; @@ -23,6 +26,18 @@ struct ops_provider { if (!ops::matmul::compatible(*crtp_this(), rhs)) throw std::runtime_error("tensor shape mismatch"); return { *crtp_this(), std::forward(rhs) }; } + + template + unary_expression> apply(Func&& func) { + if (!ops::apply::compatible(*crtp_this())) throw std::runtime_error("tensor shape mismatch"); + return { *crtp_this(), std::forward(func) }; + } + + template + binary_expression> apply(R&& rhs, Func&& func) { + if (!ops::apply::compatible(*crtp_this(), rhs)) throw std::runtime_error("tensor shape mismatch"); + return { *crtp_this(), std::forward(rhs), std::forward(func) }; + } private: decltype(auto) crtp_this() { return reinterpret_cast(this); } }; @@ -38,7 +53,7 @@ struct unary_expression : expression_tag, ops_provider> constexpr auto shape() const { return expr.shape(); } - auto coeff(std::size_t index) const { return Op{}(index, std::as_const(expr)); } + auto coeff(std::size_t index) const { return op(index, std::as_const(expr)); } }; template @@ -53,7 +68,7 @@ struct binary_expression : expression_tag, ops_provider +struct apply { + Func func; + + template >> + apply(Fwd&& fwd) // NOLINT + : func(std::forward(fwd)) {} + + template + static constexpr bool compatible(const E& expr) { + return true; + } + + template + static constexpr bool compatible(const L& lhs, const R& rhs) { + return lhs.shape() == rhs.shape(); + } + + template + static constexpr auto shape(const E& expr) { + if (!compatible(expr)) throw std::runtime_error("uncompatible operands"); + return expr.shape(); + } + + template + static constexpr auto shape(const L& lhs, const R& rhs) { + if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands"); + + using lhs_shape = remove_cvref_t; + using rhs_shape = remove_cvref_t; + + constexpr std::size_t lhs_rows = lhs_shape::template sget<0>(); + constexpr std::size_t rhs_cols = rhs_shape::template sget<1>(); + + if constexpr (lhs_rows == dynamic_extent || rhs_cols == dynamic_extent) { + return dynamic_shape{}; + } else { + return static_shape{}; + } + } + + template + constexpr auto operator()(std::size_t index, const E& expr) const { + return func(expr.coeff(index)); + } + + template + constexpr auto operator()(std::size_t index, const L& lhs, const R& rhs) const { + return func(lhs.coeff(index), rhs.coeff(index)); + } +}; + } // namespace ops } // namespace math } // namespace cenet