1 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
2 //
3 // lower_tri.h: Rcpp R/C++ interface class library -- lower.tri
4 //
5 // Copyright (C) 2010 - 2017 Dirk Eddelbuettel and Romain Francois
6 // Copyright (C) 2017    Dirk Eddelbuettel, Romain Francois, and Nathan Russell
7 //
8 // This file is part of Rcpp.
9 //
10 // Rcpp is free software: you can redistribute it and/or modify it
11 // under the terms of the GNU General Public License as published by
12 // the Free Software Foundation, either version 2 of the License, or
13 // (at your option) any later version.
14 //
15 // Rcpp is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with Rcpp.  If not, see <http://www.gnu.org/licenses/>.
22 
23 #ifndef Rcpp__sugar__lower_tri_h
24 #define Rcpp__sugar__lower_tri_h
25 
26 namespace Rcpp {
27 namespace sugar {
28 
29 template <int RTYPE, bool NA, typename T>
30 class LowerTri : public MatrixBase<LGLSXP, false, LowerTri<RTYPE, NA, T> > {
31 public:
32     typedef Rcpp::MatrixBase<RTYPE, NA, T> MatBase;
33 
LowerTri(const T & lhs,bool diag)34     LowerTri(const T& lhs, bool diag)
35         : nr(lhs.nrow()),
36           nc(lhs.ncol()),
37           getter(diag ? (&LowerTri::get_diag_true) : (&LowerTri::get_diag_false))
38     {}
39 
operator()40     inline int operator()(int i, int j) const { return get(i, j); }
41 
size()42     inline R_xlen_t size() const { return static_cast<R_xlen_t>(nr) * nc; }
nrow()43     inline int nrow() const { return nr; }
ncol()44     inline int ncol() const { return nc; }
45 
46 private:
47     typedef bool (LowerTri::*Method)(int, int) const;
48 
49     int nr, nc;
50     Method getter;
51 
get_diag_true(int i,int j)52     inline bool get_diag_true(int i, int j) const { return i >= j; }
53 
get_diag_false(int i,int j)54     inline bool get_diag_false(int i, int j) const { return i > j; }
55 
get(int i,int j)56     inline bool get(int i, int j) const { return (this->*getter)(i, j); }
57 };
58 
59 } // sugar
60 
61 template <int RTYPE, bool NA, typename T>
62 inline sugar::LowerTri<RTYPE, NA, T>
63 lower_tri(const Rcpp::MatrixBase<RTYPE, NA, T>& lhs, bool diag = false) {
64     return sugar::LowerTri<RTYPE, NA, T>(lhs, diag);
65 }
66 
67 } // Rcpp
68 
69 #endif // Rcpp__sugar__lower_tri_h
70