-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcppally.Rmd
More file actions
1082 lines (832 loc) · 28.5 KB
/
Copy pathcppally.Rmd
File metadata and controls
1082 lines (832 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Getting started with cppally"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Getting started with cppally}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
cache = FALSE
)
```
```{r, include = FALSE}
required <- c("bench", "brio", "callr", "cli", "decor",
"desc", "glue", "purrr", "readr", "stringr",
"utils", "vctrs", "withr")
if (!all(vapply(required, requireNamespace, logical(1), quietly = TRUE))) {
knitr::opts_chunk$set(eval = FALSE)
knitr::knit_exit()
}
```
Let's briefly show some of the capabilities of cppally, from its custom
C++ scalar and vectors, to using templates and concepts.
## Setup
Let's start by loading cppally
```{r}
library(cppally)
```
```{r, include=FALSE}
# Helpers to compile all examples in debug mode
cpp_source <- function(..., code, debug = TRUE, env = parent.frame()){
preamble <- c("#include <cppally.hpp>", "using namespace cppally;")
code <- paste(c(preamble, code), collapse = "\n")
cppally::cpp_source(debug = debug, env = env, code = code, ...)
}
cpp_eval <- function(..., debug = TRUE, env = parent.frame()){
cppally::cpp_eval(debug = debug, env = env, ...)
}
# Helpers to source and display C++/R code
chunk_impl <- function(x, language){
paste0("```", language, "\n", x, "\n```\n")
}
as_code_chunk <- function(x, language){
cat(chunk_impl(x, language))
}
as_cpp_chunk <- function(x){
as_code_chunk(x, "cpp")
}
# Pre-register named single-line expressions so they can be referenced later
register_single_exprs <- function(exprs, env = parent.frame(), ...){
if (is.null(names(exprs))){
stop("`exprs` must be named")
}
utils::getFromNamespace("source_single_exprs", "cppally")(
exprs, env = env, ...
)
wrappers <- setNames(
lapply(seq_along(exprs), \(i) {
fn <- get(paste0("f", i), envir = env)
function() {
out <- fn()
if (out[["is_void"]]) invisible() else out$result
}
}),
names(exprs)
)
list2env(wrappers, envir = env)
invisible()
}
```
```{r, include=FALSE}
# Compile necessary examples in one-go
# as it's faster when building the vignette
examples <- c(
hello_world = '
[[cppally::register]]
void hello_world(){
print("Hello World!");
}',
lgl_ops = '
[[cppally::register]]
r_vec<r_lgl> lgl_ops(){
return make_vec<r_lgl>(
r_true || r_false, // true
r_true && r_false, // false
r_na || r_true, // true
r_na && r_true, // NA
r_na && r_false, // false
r_na || r_na, // NA
r_na && r_na // NA
);
}
',
bad_lgl_print = '
[[cppally::register]]
void bad_lgl_print(r_lgl condition){
if (condition){
print("true");
} else {
print("false");
}
}
',
good_lgl_print = '
[[cppally::register]]
void good_lgl_print(r_lgl condition){
if (is_na(condition)){
print("NA");
} else if (condition){
print("true");
} else {
print("false");
}
}
',
also_good_lgl_print = '
[[cppally::register]]
void also_good_lgl_print(r_lgl condition){
if (condition.is_true()){
print("true");
} else {
print("not true");
}
}
',
cppally_equality = '
[[cppally::register]]
void cppally_equality(){
r_int x = na<r_int>();
r_int y = na<r_int>();
r_lgl x_equal_to_y = x == y;
if ( x_equal_to_y.is_true() ){ // NA so not printed
print("x is equal to y\\n");
}
if ( x_equal_to_y.is_false() ){ // NA so not printed
print("x is not equal to y\\n");
}
if (is_na(x_equal_to_y)){
print("`x == y` produces `NA`\\n");
}
if (identical(x, y)){
print("x is identical to y\\n");
}
}
',
cppally_identical = '
template <typename T, typename U>
[[cppally::register]]
bool cpp_identical(T x, U y){
return identical(x, y);
}
',
new_integer_vector = '
// Integer vector of size n
[[cppally::register]]
r_vec<r_int> new_integer_vector(int n){
r_vec<r_int> int_vctr(n, /*fill = */ r_int(0));
return int_vctr;
}
',
all_vectors = '
[[cppally::register]]
r_vec<r_sexp> all_vectors(){
return make_vec<r_sexp>(
arg("logical") = r_vec<r_lgl>(),
arg("integer") = r_vec<r_int>(),
arg("integer64") = r_vec<r_int64>(), // Requires bit64
arg("double") = r_vec<r_dbl>(),
arg("character") = r_vec<r_str>(),
arg("character") = r_vec<r_str_view>(),
arg("raw") = r_vec<r_raw>(),
arg("date") = r_vec<r_date>(),
arg("date-time") = r_vec<r_psxct>(),
arg("list") = r_vec<r_sexp>()
);
}
',
cpp_abs = '
template <RMathType T>
[[cppally::register]]
T cpp_abs(T x){
if (is_na(x)){
return na<T>();
} else if (x < 0){
return -x;
} else {
return x;
}
}
',
scalar_default = '
// Return the default constructor result of RScalar types
template <RScalar T>
[[cppally::register]]
T scalar_default(T ptype){
return T();
}
',
double_to_int = '
[[cppally::register]]
r_int double_to_int(r_dbl x){
return as<r_int>(x);
}
',
to_int_vec = '
[[cppally::register]]
r_vec<r_int> to_int_vec(r_vec<r_dbl> x){
return as<r_vec<r_int>>(x);
}
',
coercions = '
[[cppally::register]]
r_vec<r_sexp> coercions(){
r_dbl a(4.2);
r_vec<r_dbl> b = make_vec<r_dbl>(2.5);
return make_vec<r_sexp>(
as<r_vec<r_int>>(a),
as<r_int>(a),
as<r_int>(b),
as<r_dbl>(b)
);
}
',
to_from_cpp_vec = '
[[cppally::register]]
r_vector<r_int> cpp_vectors_example(r_vector<r_int> x){
std::vector x_cpp = as<std::vector<r_int>>(x);
x_cpp.push_back(r_int(42));
return as<r_vector<r_int>>(x_cpp);
}
',
str_concatenate = '
[[cppally::register]]
r_str str_concatenate(r_str x, r_str y, r_str sep){
std::string left = std::string(x.cpp_str());
std::string right = std::string(y.cpp_str());
std::string middle = std::string(sep.cpp_str());
std::string combined = left + middle + right;
return r_str(combined.c_str());
}
',
new_list = '
using list = r_vec<r_sexp>;
[[cppally::register]]
list new_list(int n){
return list(n);
}
',
resize_all = '
[[cppally::register]]
r_vec<r_sexp> resize_all(r_vec<r_sexp> x, r_size_t n){
r_size_t list_length = x.length();
for (r_size_t i = 0; i < list_length; ++i){
r_sexp_visit(x.view(i), [&]<RVector T>(T vec) {
x.set(i, vec.resize(n));
});
}
return x;
}
',
new_factor = '
[[cppally::register]]
r_factors new_factor(r_vec<r_str> x){
return r_factors(x);
}
',
factor_codes = '
static_assert(!RVector<r_factors>);
[[cppally::register]]
r_vec<r_int> factor_codes(r_factors x){
return x.codes();
}
',
setnames = '
[[cppally::register]]
r_vec<r_sexp> set_list_names(r_vec<r_sexp> x, r_vec<r_str> names){
x.set_names(names);
return x;
}
'
)
# Benchmarks need debug = FALSE
benchmark_examples <- c(
cpp_n_unique = '
template <RVector T>
[[cppally::register]]
r_int cpp_n_unique(T x){
return as<r_int>(n_unique(x));
}
',
primitive_sum = '
[[cppally::register]]
double primitive_sum(const r_vec<r_dbl>& x){
// r_vec<T>::data_type always returns typename T
using data_t = typename std::remove_cvref_t<decltype(x)>::data_type;
using primitive_t = unwrap_t<data_t>;
primitive_t *p_x = x.data();
r_size_t n = x.length();
double sum = 0;
OMP_SIMD_REDUCTION1(+:sum)
for (r_size_t i = 0; i < n; ++i){
sum += p_x[i];
}
return sum;
}
'
)
cpp_source(code = paste(examples, collapse = "\n"), debug = TRUE)
cpp_source(code = paste(benchmark_examples, collapse = "\n"), debug = FALSE)
# Single-line expressions, pre-registered as R functions of the same name.
# Each can be invoked later as e.g. `r_true_val()` to get the evaluated result.
single_exprs <- c(
r_true_val = 'r_true',
r_false_val = 'r_false',
r_na_val = 'r_na',
make_vec_dbl = 'make_vec<r_dbl>(1, 1.5, 2, na<r_dbl>())',
make_vec_dbl_named = '
make_vec<r_dbl>(
arg("first") = 1,
arg("second") = 1.5,
arg("third") = 2,
arg("last") = na<r_dbl>()
)
',
make_vec_sexp = 'make_vec<r_sexp>(1, 2, 3)',
r_str_hello = 'r_str("hello")',
r_str_hello_c_str = 'r_str("hello").c_str()',
r_sym_new = 'r_sym("new_symbol")',
r_sym_from_str = 'r_sym(r_str("symbol_from_string"))',
cached_str_demo = 'cached_str<"cached_string">()',
cached_sym_demo = 'cached_sym<"cached_symbol">()'
)
register_single_exprs(single_exprs, debug = TRUE)
```
## Registering R functions
To make a C++ function available to R we use the `[[cppally::register]]` tag.
``` cpp
#include <cppally.hpp>
using namespace cppally;
[[cppally::register]]
void hello_world(){
print("Hello World!");
}
```
After tagging our functions we want to make them available to R. To do that we have a few routes.
### Registering C++ functions outside of a package context
After writing our hello world program in foo.cpp we can use `cpp_source()` to compile and register the function to R.
```r
cpp_source(file = "src/foo.cpp")
```
Now the function is available in R
```{r}
hello_world()
```
Similarly we can use the helper `cpp_eval` to run simple expressions and return
the result without needing to include cppally.hpp and register the function.
```{r}
cpp_eval('print("Hello World Again!")')
```
**Note** - For the rest of the examples it is assumed that the following code
is always included beforehand.
```cpp
#include <cppally.hpp>
using namespace cppally;
```
### Registering C++ functions inside a cppally-linked package
Since cppally is header-only, we can include the headers directly into our own package.
### General steps to using cppally in a package
1. Create package (if you haven't already done so) using `usethis::create_tidy_package()`
2. Run `cppally::use_cppally()`
3. Run `cppally::document()`
This will automatically add the necessary package content needed to start working with cppally. For continuous development, use `cppally::load_all()` to compile and register cppally tagged functions, including our hello world function.
**Note:** We aim to integrate cppally registration into the `devtools` framework for ease-of-use.
## C++ types
cppally offers a rich set of R types in C++ that are NA-aware. This means that common arithmetic and logical operations will account for `NA` in a similar fashion to R.
## Scalars
### logical scalar - `r_lgl`
cppally's scalar version of `logical`, `r_lgl` can represent true, false or NA.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(paste(
single_exprs[["r_true_val"]],
single_exprs[["r_false_val"]],
single_exprs[["r_na_val"]],
sep = "\n"
))
```
```{r, echo=FALSE}
r_true_val()
r_false_val()
r_na_val()
```
Logical operators work just like in R
```{r, echo=FALSE, comment="", results='asis'}
as_cpp_chunk(examples[["lgl_ops"]])
```
```{r}
lgl_ops()
```
**Using `r_lgl`** in if-statements
For type-safety reasons `r_lgl` cannot be implicitly converted to `bool` except in if-statements where an error is thrown if the value is `NA`.
**DON'T** do this:
```{r, echo=FALSE, comment="", results='asis'}
as_cpp_chunk(examples[["bad_lgl_print"]])
```
```{r, error=TRUE}
bad_lgl_print(TRUE)
bad_lgl_print(FALSE)
bad_lgl_print(NA) # Can't implicitly convert NA to bool
```
**DO** this:
```{r, echo=FALSE, comment="", results='asis'}
as_cpp_chunk(examples[["good_lgl_print"]])
```
```{r}
good_lgl_print(TRUE)
good_lgl_print(FALSE)
good_lgl_print(NA) # NA is handled explicitly so no issues
```
We can also use `r_lgl` members `is_true()` and `is_false()` which return `bool` and
are equivalent to R's `isTRUE()` and `isFALSE()`
```{r, echo=FALSE, comment="", results='asis'}
as_cpp_chunk(examples[["also_good_lgl_print"]])
```
```{r}
also_good_lgl_print(TRUE)
also_good_lgl_print(FALSE)
also_good_lgl_print(NA) # Falls into 'not true' branch here as expected
```
All cppally scalar types are implemented as structs that contain the underlying C/C++ types as well as other member functions.
| cppally type | Description | Implicitly converts to |
| :------------ | --------------------------- | :------------------------------- |
| `r_lgl` | Scalar logical | `bool` **only** in if-statements |
| `r_int` | Scalar integer | `int` |
| `r_int64` | Scalar 64-bit integer | `int64_t` |
| `r_dbl` | Scalar double | `double` |
| `r_str` | Scalar string | `SEXP` |
| `r_cplx` | Scalar double complex | `std::complex<double>` |
| `r_raw` | Scalar raw | `unsigned char` |
| `r_sym` | Symbol | `SEXP` |
| `r_date` [^1] | Scalar date | `double` |
| `r_psxct` | Scalar date-time | `double` |
| `r_sexp` | Generic R object (SEXP)[^2] | `SEXP` |
[^1]: Unlike `r_str` which is composite and holds an `r_sexp` member, `r_date` and `r_psxct` instead inherit directly from `r_dbl`. This means that they can implicitly convert to `r_dbl`
[^2]: `r_sexp` represents a generic R object which can include cppally vectors. We will explain how to disambiguate `r_sexp` later which is most useful when working with lists and data frames
`NA` values can be accessed via the template function `na<T>`
### C++ NA values and their R C API equivalents
| Type | Value | R C API Value | constexpr?[^3] |
| ------------------------ | --------------------- | -------------- | -------------- |
| `r_lgl` | `na<r_lgl>()`/`r_na` | `NA_LOGICAL` | Yes |
| `r_int` | `na<r_int>()` | `NA_INTEGER` | Yes |
| `r_int64` | `na<r_int64>()` | Not applicable | Yes |
| `r_dbl` | `na<r_dbl>()` | `NA_REAL` | Yes |
| `r_str` | `na<r_str>()` | `NA_STRING` | No |
| `r_cplx` | `na<r_cplx>()` | Not applicable | Yes |
| `r_sym` | Not applicable | Not applicable | No |
| `r_sexp`[^4]<br><br><br> | `na<r_sexp>`/`r_null` | `R_NilValue` | No |
[^3]: In C++ constexpr is used as a keyword to declare that it's at least sometimes possible to evaluate values at compile-time, meaning they are known before any code is run by the user.
[^4]: Having an `NA` sentinel for `r_sexp` is very useful when writing templates involving vectors. For this reason the `NA` sentinel is `r_null`. This doesn't mean `is_na(r_null)` is true, and is intentionally not true because it is not a scalar and therefore cannot be `NA`. As `r_null` represents the absence of a tangible R object, it can be thought of as a zero-length object and since all `NA` values are represented as length-1 vectors (in R), `is_na(r_null)` should not return true.
## Checking equality
There are two ways to check for equality of cppally scalars -
with the `==` operator or with `identical()`.
The cppally `==` operator always returns `r_lgl` and `identical()` always
returns `bool`, which is a particularly important distinction
when dealing with `NA` values.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["cppally_equality"]])
```
```{r}
cppally_equality()
```
`identical()` can compare scalars, vectors, lists, factors, and data frames
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["cppally_identical"]])
```
```{r}
cpp_identical(3L, 3L)
cpp_identical(NA, NA)
cpp_identical(3L, 3) # int != double
cpp_identical(1:10, 1:10)
cpp_identical(list(1, 2, 3), list(3, 2, 1))
cpp_identical(iris, iris)
```
## Vectors
cppally vectors are templated and can be thought of as containers of scalar
elements like `r_int`, `r_dbl`, etc.
**Note:** `r_vector` is an alias of `r_vec` so both can be used.
We can create vectors like so
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["new_integer_vector"]])
```
```{r}
new_integer_vector(3)
```
### inline vectors
To create inline vectors, use `make_vec<>`
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["make_vec_dbl"]])
```
```{r, echo=FALSE}
make_vec_dbl()
```
We can add names on the fly with `arg()`
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["make_vec_dbl_named"]])
```
```{r, echo=FALSE}
make_vec_dbl_named()
```
In R a list is a generic vector, so cppally defines lists as `r_vec<r_sexp>`, a vector of the generic type `r_sexp`.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["make_vec_sexp"]])
```
```{r, echo=FALSE}
make_vec_sexp()
```
A list of all cppally vectors of length 0
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["all_vectors"]])
```
```{r}
all_vectors()
```
## Coercion
To coerce from one scalar to another we can use `as<T>`
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["double_to_int"]])
```
```{r}
double_to_int(pi)
double_to_int(NA_real_)
```
We can also coerce from one vector type to another
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["to_int_vec"]])
```
```{r}
to_int_vec(c(0, 1.5, NA))
```
Since `as<T>` is extremely flexible, we can also coerce
from a scalar to a vector or vice versa
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["coercions"]])
```
```{r}
coercions()
```
We can even coerce to and from C++ vectors
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["to_from_cpp_vec"]])
```
```{r}
cpp_vectors_example(41L)
```
While coercing to a `std::vector` just to push back an element before coercing back might not be the most efficient, it does showcase how easy it is to work with
cppally vectors and C++ vectors.
## Strings
cppally provides the useful string type `r_str`
We can create R strings easily
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["r_str_hello"]])
```
```{r, echo=FALSE}
r_str_hello()
```
To get a C or C++ string, use the members `c_str()` and `cpp_str()` respectively
C string via `c_str()`
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["r_str_hello_c_str"]])
```
```{r, echo=FALSE}
r_str_hello_c_str()
```
C++ string_view via `cpp_str()`
This can be converted into a std::string via its constructor
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["str_concatenate"]])
```
```{r}
str_concatenate("hello", "how are you?", sep = ", ")
```
## Symbols
Symbols have class `r_sym` and can be created directly from a string literal
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["r_sym_new"]])
```
```{r, echo=FALSE}
r_sym_new()
```
Or from a cppally string
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["r_sym_from_str"]])
```
```{r, echo=FALSE}
r_sym_from_str()
```
## Cached strings & symbols
cppally provides an efficient caching strategy for constructing cppally
strings/symbols from string literals
`cached_str<>`
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["cached_str_demo"]])
```
```{r, echo=FALSE}
cached_str_demo()
```
This initialises the string once, caches it (to R's CHARSXP pool), and efficiently
re-uses the cached string for each subsequent call.
We can cache symbols in a similar way
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(single_exprs[["cached_sym_demo"]])
```
```{r, echo=FALSE}
cached_sym_demo()
```
## Lists
`r_sexp` is generally interpreted as an "element of a list" since lists are defined as `r_vec<r_sexp>`, a vector that holds generic `r_sexp` elements.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["new_list"]])
```
```{r}
new_list(0)
new_list(3)
```
The problem with a class like `r_sexp` is that it is by design
generic and therefore difficult to work with in C++.
To disambiguate the actual type we can use `r_sexp_visit()` via a C++ lambda.
**Example:** using `r_sexp_visit()` to resize every vector to length n in-place
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["resize_all"]])
```
## Factors
We can create a factor via `r_factors()`
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["new_factor"]])
```
```{r}
new_factor(letters)
```
In cppally, like R, factors are not vectors and therefore do not satisfy the RVector concept. To access the underlying integer codes vector, use the public `codes()` member function
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["factor_codes"]])
```
```{r}
letter_fct <- new_factor(letters)
letter_fct |>
factor_codes()
```
## Concepts and Templates
One of the most powerful features of C++20 are concepts. These allow users to write human-readable templates and constraints.
When writing your own templates, it is necessary to place them in headers
for cppally registration to work correctly.
Let's practice by creating the `abs()` function in C++ using templates
and the `RMathType` concept.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["cpp_abs"]])
```
What's nice is that it works correctly for integers and doubles
while simultaneously preserving their type
```{r}
cpp_abs(-4.2)
cpp_abs(-3L)
class(cpp_abs(-4.2)) # Double preserved
class(cpp_abs(-3L)) # Integer preserved
```
This type of programming is historically tricky within the R C API and
typically necessitates a switch statement that switches on the object's type,
handling each type separately. With our `abs()` template, the logic is
correctly handled with one set of operations.
### How it works
The top-line `template <RMathType T>` declares a template that encapsulates `T`, an `RMathType` - a concept that contains `r_lgl`, `r_int`, `r_int64` and `r_dbl`
If x is NA then we immediately also return NA via `na<T>()` which is a templated
function that returns NA of the input type `T`.
To correctly register templates, the '[[cppally::register]]' tag must
always go above the function name.
```cpp
template <typename T>
[[cppally::register]] // <--- Here
T foo(T x){
return x;
}
```
### Templates without function arguments
Explicit instantiation (from R) is unfortunately not possible and template
types must be deduced from supplied arguments.
```cpp
template <typename T>
[[cppally::register]]
T foo(){
return T();
}
```
Here `foo()` will not be compiled because the function has no arguments that let
the compiler automatically deduce what `T` is. In C++ you would call always
call this function like so: `foo<T>()`.
Unfortunately we can't do that from R directly.
You may get a cryptic compiler error like this
```cpp
error: no matching function for call to 'foo()'
[]<typename T>() -> decltype(cpp_to_r(::foo())) {
```
along with an equally cryptic note
```cpp
note: couldn't deduce template parameter 'T'
[]<typename T>() -> decltype(cpp_to_r(::foo())) {
```
Even though these kinds of templates can be written with cppally in C++,
they cannot be exported to R.
An obvious and somewhat ugly workaround is to include a prototype argument that
allows the template parameter to be deduced from.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["scalar_default"]])
```
```{r}
scalar_default(integer(1)) # Default is 0L
scalar_default(numeric(1)) # Default is 0.0
scalar_default(character(1)) # Default is ""
```
Exporting variadic templates are also not supported. The best alternative is
to use lists (`r_vec<r_sexp>`).
In the above example we used the `RScalar` concept which includes
all cppally scalar types (excluding `r_sexp`).
For a list of all cppally concepts, please see the **Annex**
## Attributes
Attributes can be manipulated via functions defined in the attr namespace.
**Example:** Adding names to a list
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(examples[["setnames"]])
```
```{r}
set.seed(42)
norm_samples <- lapply(1:5, \(x) rnorm(10, mean = x))
set_list_names(norm_samples, paste0("sample_", 1:5))
```
More useful attribute helpers
- `get_attrs()` - Returns a list of attributes (possibly `r_vec<r_sexp>(r_null)`)
- `set_attrs()` - Sets attributes to ones specified. Note: replaces any current attributes
- `clear_attrs()` - Removes all attributes
- `set_attr()` - Set a single attribute
- `get_attr()` - Get a single attribute
- `inherits1()` - Does object inherit class?
- `inherits_any()` - Does object inherit at least one of the specified classes?
- `inherits_all()` - Does object inherit all of the specified classes?
- `modify_attrs()` - Modifies current attributes but doesn't remove any existing ones
## Sugar functions
cppally also offers many useful and high-performance common functions in cppally/sugar
**Example:** `n_unique()` - fast calculation of number of unique values.
```{r, echo=FALSE, results = 'asis'}
as_cpp_chunk(benchmark_examples[["cpp_n_unique"]])
```
```{r}
library(bench)
x <- sample(1:100, 10^5, replace = TRUE)
mark(
base_n_unique = length(unique(x)),
cppally_n_unique = cpp_n_unique(x)
)
```
More useful sugar functions
- `unique()` - Like R's `unique()` but with a `sort` argument to return sorted unique values
- `match()` - Like R's match, but also faster
- `order()` - Like base R's order but it internally uses a hybrid approach of ska sort, count sorting, quick sort, etc.
- `make_groups()` - An advanced function that returns a struct containing group IDs and number of groups (i.e number of unique group IDs). The `groups` struct contains the following members:
- r_vec<r_int> ids - The cached group IDs
- int n_groups - Number of unique groups
- bool ordered - Do the group IDs specify a sorting order, or are they by order-of-first-appearance?
- bool sorted - Are the group IDs sorted? (This can also be true for order-of-first-appearance IDs)
- r_vec<r_int> start() - Returns an r_vec<r_int>(n_groups) vector of start locations of each unique group, signifying the location in the data at which each group initially appeared
- r_vec<r_int> counts() - Returns an r_vec<r_int>(n_groups) vector of frequency counts of each unique group
- r_vec<r_int> order() - Returns an r_vec<r_int>(ids.length()) order vector. This is a 0-indexed permutation vector that can be used to return sorted group IDs
- `recycle()` - Recycles supplied vectors to common length
- `r_vec<T>::subset()` - Fast subsetting of vectors
**Scalar math functions**
There is a rich suite of math functions. Some examples include `min()`, `max()`, `round()`, `log()`, `floor()`, `ceiling()` and more.
**Stats sugar functions**