| 1 | // Copyright Louis Dionne 2013-2022 |
| 2 | // Distributed under the Boost Software License, Version 1.0. |
| 3 | // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) |
| 4 | |
| 5 | #ifndef BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP |
| 6 | #define BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP |
| 7 | |
| 8 | #include <boost/hana/equal.hpp> |
| 9 | #include <boost/hana/eval_if.hpp> |
| 10 | #include <boost/hana/front.hpp> |
| 11 | #include <boost/hana/functional/always.hpp> |
| 12 | #include <boost/hana/functional/fix.hpp> |
| 13 | #include <boost/hana/functional/flip.hpp> |
| 14 | #include <boost/hana/functional/on.hpp> |
| 15 | #include <boost/hana/functional/partial.hpp> |
| 16 | #include <boost/hana/integral_constant.hpp> |
| 17 | #include <boost/hana/plus.hpp> |
| 18 | #include <boost/hana/power.hpp> |
| 19 | #include <boost/hana/range.hpp> |
| 20 | #include <boost/hana/remove_at.hpp> |
| 21 | #include <boost/hana/transform.hpp> |
| 22 | #include <boost/hana/tuple.hpp> |
| 23 | #include <boost/hana/unpack.hpp> |
| 24 | |
| 25 | #include <utility> |
| 26 | |
| 27 | #include "matrix.hpp" |
| 28 | |
| 29 | |
| 30 | namespace cppcon { |
| 31 | namespace hana = boost::hana; |
| 32 | auto det = hana::fix([](auto det, auto&& m) -> decltype(auto) { |
| 33 | auto matrix_minor = [=](auto&& m, auto i, auto j) -> decltype(auto) { |
| 34 | return det(hana::unpack( |
| 35 | hana::transform( |
| 36 | hana::remove_at(rows(std::forward<decltype(m)>(m)), i), |
| 37 | hana::partial(hana::flip(hana::remove_at), j) |
| 38 | ), |
| 39 | matrix |
| 40 | )); |
| 41 | }; |
| 42 | |
| 43 | auto cofactor = [=](auto&& m, auto i, auto j) { |
| 44 | return hana::power(hana::int_c<-1>, hana::plus(i, j)) * |
| 45 | matrix_minor(std::forward<decltype(m)>(m), i, j); |
| 46 | }; |
| 47 | |
| 48 | return hana::eval_if(m.size() == hana::size_c<1>, |
| 49 | hana::always(m.at(hana::size_c<0>, hana::size_c<0>)), |
| 50 | [=](auto _) { |
| 51 | auto cofactors_1st_row = hana::unpack(_(hana::make_range)(hana::size_c<0>, m.ncolumns()), |
| 52 | hana::on(hana::make_tuple, hana::partial(cofactor, m, hana::size_c<0>)) |
| 53 | ); |
| 54 | return detail::tuple_scalar_product(hana::front(rows(m)), cofactors_1st_row); |
| 55 | } |
| 56 | ); |
| 57 | }); |
| 58 | } // end namespace cppcon |
| 59 | |
| 60 | #endif // !BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP |
| 61 | |