-
Notifications
You must be signed in to change notification settings - Fork 118
/
21_Translating_R_code.Rmd
executable file
·1084 lines (863 loc) · 30.2 KB
/
21_Translating_R_code.Rmd
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
```{r, include = FALSE}
source("common.R")
```
# Translating R code
<!-- 21 -->
## Prerequisites {-}
<!-- 21.0 -->
In this chapter we combine R's metaprogramming and functional programming capabilities and therefore load both the `{rlang}` and the `{purrr}` package.
```{r setup, message = FALSE}
library(rlang)
library(purrr)
```
\stepcounter{section}
## HTML
<!-- 21.2 -->
__[Q1]{.Q}__: The escaping rules for `<script>` tags are different because they contain JavaScript, not HTML. Instead of escaping angle brackets or ampersands, you need to escape `</script>` so that the tag isn't closed too early. For example, `script("'</script>'")`, shouldn't generate this:
```{html}
<script>'</script>'</script>
```
But
```{html}
<script>'<\/script>'</script>
```
Adapt the `escape()` to follow these rules when a new argument `script` is set to `TRUE`.
__[A]{.solved}__: We are asked to implement a special case of escaping for the `<script>` tag. At first we will revisit the relevant functions provided in *Advanced R* and confirm that our code reliably escapes for tags like `<p>` and `<b>` but doesn't escape correctly for the `<script>` tag. Then we modify the `escape()` and `tag()` functions to redefine the `<script>` tag and confirm that all defined tags now escape correctly.
Note that the `<style>` tag, which contains styling information in CSS, follows the same escaping rules as the `<script>` tag. We therefore implement the desired escaping for the `<style>` tag function also.
Let's start by loading the relevant code from *Advanced R* first.
```{r required code from advr}
# Escaping
html <- function(x) structure(x, class = "advr_html")
print.advr_html <- function(x, ...) {
out <- paste0("<HTML> ", x)
cat(paste(strwrap(out), collapse = "\n"), "\n", sep = "")
}
escape <- function(x) UseMethod("escape")
escape.character <- function(x) {
x <- gsub("&", "&", x)
x <- gsub("<", "<", x)
x <- gsub(">", ">", x)
html(x)
}
escape.advr_html <- function(x) x
# Basic tag functions
dots_partition <- function(...) {
dots <- list2(...)
if (is.null(names(dots))) {
is_named <- rep(FALSE, length(dots))
} else {
is_named <- names(dots) != ""
}
list(
named = dots[is_named],
unnamed = dots[!is_named]
)
}
# html_attributes() function from the GitHub repository of Advanced R
# https://github.com/hadley/adv-r/blob/master/dsl-html-attributes.r
html_attributes <- function(list) {
if (length(list) == 0) return("")
attr <- map2_chr(names(list), list, html_attribute)
paste0(" ", unlist(attr), collapse = "")
}
html_attribute <- function(name, value = NULL) {
if (length(value) == 0) return(name) # for attributes with no value
if (length(value) != 1) stop("`value` must be NULL or length 1")
if (is.logical(value)) {
# Convert T and F to true and false
value <- tolower(value)
} else {
value <- escape_attr(value)
}
paste0(name, "='", value, "'")
}
escape_attr <- function(x) {
x <- escape.character(x)
x <- gsub("\'", ''', x)
x <- gsub("\"", '"', x)
x <- gsub("\r", ' ', x)
x <- gsub("\n", ' ', x)
x
}
# Tag functions
tag <- function(tag) {
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
attribs <- html_attributes(dots$named)
children <- map_chr(dots$unnamed, escape)
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env()
)
}
```
This code escapes the `<p>` and `<b>` tags correctly, but doesn't achieve the desired behaviour for the `<script>` tag yet:
```{r}
p <- tag("p")
b <- tag("b")
identical(
p("&","and <", b("& > will be escaped")) %>%
as.character(),
"<p>&and <<b>& > will be escaped</b></p>"
)
script <- tag("script")
identical(
script("Don't escape &, <, > - escape </script> and </style>") %>%
as.character(),
paste("<script>Don't escape &, <, >",
"- escape <\\/script> and <\\/style></script>")
)
```
We implement the desired change and add the optional argument `script` to the `escape()` and the `tag()` functions (default: `script = FALSE`). The argument has to be added for all methods of the `escape()` generic.
```{r}
escape <- function(x, script = FALSE) UseMethod("escape")
escape.character <- function(x, script = FALSE) {
if (script) {
x <- gsub("</script>", "<\\/script>", x, fixed = TRUE)
x <- gsub("</style>", "<\\/style>", x, fixed = TRUE)
} else {
x <- gsub("&", "&", x)
x <- gsub("<", "<", x)
x <- gsub(">", ">", x)
}
html(x)
}
escape.advr_html <- function(x, script = FALSE) x
tag <- function(tag, script = FALSE) {
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
attribs <- html_attributes(dots$named)
children <- map_chr(dots$unnamed, escape, script = !!script)
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env()
)
}
```
Finally, we create new `<p>`, `<b>` and `<script>` tag functions, which now pass their escaping tests.
```{r}
p <- tag("p")
b <- tag("b")
identical(
p("&","and <", b("& > will be escaped")) %>%
as.character(),
"<p>&and <<b>& > will be escaped</b></p>"
)
script <- tag("script", script = TRUE)
style <- tag("style" , script = TRUE)
identical(
script("Don't escape &, <, > - escape </script> and </style>") %>%
as.character(),
paste("<script>Don't escape &, <, >",
"- escape <\\/script> and <\\/style></script>")
)
script("Don't escape &, <, > - escape </script> and </style>")
```
__[Q2]{.Q}__: The use of `...` for all functions has some big downsides. There's no input validation and there will be little information in the documentation or autocomplete about how they are used in the function. Create a new function that, when given a named list of tags and their attribute names (like below), creates tag functions with named arguments.
```{r, eval = FALSE}
list(
a = c("href"),
img = c("src", "width", "height")
)
```
All tags should get `class` and `id` attributes.
__[A]{.solved}__: This exercise requires a function factory: The named list of attribute names will be extended (by `class` and `id`) and mapped to function arguments. These will default to `NULL`, so that the user isn't forced to provide them.
When creating the tag functions itself we use `check_dots_unnamed()` from the `{ellipsis}` package to ensure named arguments correspond to the expected values (and are not created by some spelling mistake). After that we follow the logic from the `tag()` function factory above.
To keep the focus on the key ideas, we ignore special cases like `<script>`, `<style>` and void tags in this solution (even if this leads to an incorrect tag function for the `<img>` tag).
```{r}
tag_factory <- function(tag, tag_attrs) {
attrs <- c("class", "id", tag_attrs)
attr_args <- set_names(rep(list(NULL), length(attrs)), attrs)
attr_list <- call2("list", !!!syms(set_names(attrs)))
new_function(
exprs(... = , !!!attr_args),
expr({
ellipsis::check_dots_unnamed()
attribs <- html_attributes(compact(!!attr_list))
dots <- compact(list(...))
children <- map_chr(dots, escape)
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
})
)
}
```
To validate our new function factory, we modify the `with_html()` example from *Advanced R* to work with our newly created `a()` and `img()` tag functions.
```{r}
tag_list <- list(
a = c("href"),
img = c("src", "width", "height")
)
tags <- map2(names(tag_list), unname(tag_list), tag_factory) %>%
set_names(names(tag_list))
with_tags <- function(code) {
code <- enquo(code)
eval_tidy(code, tags)
}
with_tags(
a(
img("Correct me if I am wrong", id = "second"),
href = "https://github.com/Tazinho/Advanced-R-Solutions/issues",
id = "first"
)
)
```
__[Q3]{.Q}__: Reason about the following code that calls `with_html()` referencing objects from the environment. Will it work or fail? Why? Run the code to verify your predictions.
```{r, eval = FALSE}
greeting <- "Hello!"
with_html(p(greeting))
p <- function() "p"
address <- "123 anywhere street"
with_html(p(address))
```
__[A]{.solved}__: First, we rerun the relevant code from *Advanced R* to define `with_html()`. Note that we skip the code for void tags, as none of them appear in the code chunk from this exercise.
```{r}
tags <- c(
"a", "abbr", "address", "article", "aside", "audio",
"b", "bdi", "bdo", "blockquote", "body", "button", "canvas",
"caption", "cite", "code", "colgroup", "data", "datalist",
"dd", "del", "details", "dfn", "div", "dl", "dt", "em",
"eventsource", "fieldset", "figcaption", "figure", "footer",
"form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header",
"hgroup", "html", "i", "iframe", "ins", "kbd", "label",
"legend", "li", "mark", "map", "menu", "meter", "nav",
"noscript", "object", "ol", "optgroup", "option", "output",
"p", "pre", "progress", "q", "ruby", "rp", "rt", "s", "samp",
"script", "section", "select", "small", "span", "strong",
"style", "sub", "summary", "sup", "table", "tbody", "td",
"textarea", "tfoot", "th", "thead", "time", "title", "tr",
"u", "ul", "var", "video"
)
html_tags <- tags %>% set_names() %>% map(tag)
with_html <- function(code) {
code <- enquo(code)
eval_tidy(code, html_tags)
}
```
Now, let us briefly repeat, that `with_html()` was introduced to evaluate tag functions from within a list. Otherwise, defining some tag functions like `body()`, `source()`, `summary()` etc. within the global environment would collide with base R functions with the same name. To prevent this the DSL code wrapped in `with_html()` is evaluated within the "context" of `html_tags`, which was provided as a data mask to `eval_tidy()`. As `?rlang::as_data_mask` mentions: "Objects in the mask have precedence over objects in the environment".
Therefore, `p()` refers to the tag function from `html_tags` within both examples from the exercise. However, as `address` is not only a string within the global environment, but also a tag function within `html_tags` (the `<address>` HTML tag may be used to provide contact information on an HTML page), `p()` operates on `address()` in the second example. This correctly leads to an error as we haven't implemented an `escape.function()` method.
```{r, error = TRUE}
greeting <- "Hello!"
with_html(p(greeting))
p <- function() "p"
address <- "123 anywhere street"
with_html(p(address))
```
__[Q4]{.Q}__: Currently the HTML doesn't look terribly pretty, and it's hard to see the structure. How could you adapt `tag()` to do indenting and formatting? (You may need to do some research into block and inline tags.)
__[A]{.solved}__: First, let us load all relevant functions from *Advanced R*:
```{r required code from book}
tag <- function(tag) {
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
attribs <- html_attributes(dots$named)
children <- map_chr(dots$unnamed, escape)
html(paste0(
!!paste0("<", tag), attribs, ">",
paste(children, collapse = ""),
!!paste0("</", tag, ">")
))
}),
caller_env()
)
}
void_tag <- function(tag) {
new_function(
exprs(... = ),
expr({
dots <- dots_partition(...)
if (length(dots$unnamed) > 0) {
stop(
!!paste0("<", tag, "> must not have unnamed arguments"),
call. = FALSE
)
}
attribs <- html_attributes(dots$named)
html(paste0(!!paste0("<", tag), attribs, " />"))
}),
caller_env()
)
}
tags <- c(
"a", "abbr", "address", "article", "aside", "audio", "b",
"bdi", "bdo", "blockquote", "body", "button", "canvas",
"caption", "cite", "code", "colgroup", "data", "datalist",
"dd", "del", "details", "dfn", "div", "dl", "dt", "em",
"eventsource", "fieldset", "figcaption", "figure", "footer",
"form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header",
"hgroup", "html", "i", "iframe", "ins", "kbd", "label", "legend",
"li", "mark", "map", "menu", "meter", "nav", "noscript", "object",
"ol", "optgroup", "option", "output", "p", "pre", "progress", "q",
"ruby", "rp", "rt", "s", "samp", "script", "section", "select",
"small", "span", "strong", "style", "sub", "summary", "sup",
"table", "tbody", "td", "textarea", "tfoot", "th", "thead",
"time", "title", "tr", "u", "ul", "var", "video"
)
void_tags <- c(
"area", "base", "br", "col", "command", "embed", "hr", "img",
"input", "keygen", "link", "meta", "param", "source",
"track", "wbr"
)
html_tags <- c(
tags %>% set_names() %>% map(tag),
void_tags %>% set_names() %>% map(void_tag)
)
with_html <- function(code) {
code <- enquo(code)
eval_tidy(code, html_tags)
}
```
Now, let's look at the example from above:
```{r, error = TRUE}
with_html(
body(
h1("A heading", id = "first"),
p("Some text &", b("some bold text.")),
img(src = "myimg.png", width = 100, height = 100)
)
)
```
The formatting consists of only one long line of code. This output makes it difficult to check the content of the HTML code and its correctness.
What kind of formatting would we prefer instead? [Google's HTML style guide](https://google.github.io/styleguide/htmlcssguide.html#HTML_Formatting_Rules) suggests *indentation* by 2 spaces and *new lines* for every block, list, or table element. There are other recommendations, but we will keep things simple and will be satisfied with the following output.
```{html, eval = FALSE}
<body>
<h1 id='first'>A heading</h1>
<p>Some text &<b>some bold text.</b></p>
<img src='myimg.png'width='100' height='100' />
</body>
```
First we adjust the `print.advr_html()` method, removing `strwrap()` function, because this will re-wrap the HTML, making it harder to understand what's happening.
```{r}
html <- function(x) structure(x, class = "advr_html")
print.advr_html <- function(x, ...) {
cat(paste("<HTML>", x, sep = "\n"))
}
```
In our desired output we can see that the content of the `body`-function requires different formatting than the other tag-functions. We will therefore create a new `format_code()` function, that allows for optional indentation and line breaks.
```{r}
indent <- function(x) {
paste0(" ", gsub("\n", "\n ", x))
}
format_code <- function(children, indent = FALSE) {
if (indent) {
paste0("\n", paste0(indent(children), collapse = "\n"), "\n")
} else {
paste(children, collapse = "")
}
}
```
We adjust the body function to include the `format_code()` helper. (This could also be approached programmatically in the tag function factory.)
```{r}
html_tags$body <- function(...) {
dots <- dots_partition(...)
attribs <- html_attributes(dots$named)
children <- map_chr(dots$unnamed, escape)
html(paste0(
"<body", attribs, ">",
format_code(children, indent = TRUE),
"</body>"
))
}
```
The resulting output is much more satisfying.
```{r, error = TRUE}
with_html(
body(
h1("A heading", id = "first"),
p("Some text &", b("some bold text.")),
img(src = "myimg.png", width = 100, height = 100)
)
)
```
## LaTeX
<!-- 21.3 -->
__[Q1]{.Q}__: Add escaping. The special symbols that should be escaped by adding a backslash in front of them are `\`, `$`, and `%`. Just as with HTML, you'll need to make sure you don't end up double-escaping. So, you'll need to create a small S3 class and then use that in function operators. That will also allow you to embed arbitrary LaTeX if needed.
__[A]{.solved}__: Currently our `to_math()` function generates the following output:
```{r, eval = FALSE}
to_math(`$`)
#> <LATEX> \mathrm{f}($) # instead of <LATEX> \$
to_math(a$b)
#> <LATEX> \mathrm{$}(a b) # instead of <LATEX> \mathrm{\$}(a b)
to_math(`\\`)
#> <LATEX> \mathrm{f}(\) # instead of <LATEX> \\
to_math(`%`)
#> <LATEX> \mathrm{f}(%) # instead of <LATEX> \%
```
```{r include = FALSE}
## 3.3 to_math()
to_math <- function(x) {
expr <- enexpr(x)
out <- eval_bare(expr, latex_env(expr))
latex(out)
}
latex <- function(x) structure(x, class = "advr_latex")
print.advr_latex <- function(x) {
cat("<LATEX> ", x, "\n", sep = "")
}
greek <- c(
"alpha", "theta", "tau", "beta", "vartheta", "pi", "upsilon",
"gamma", "varpi", "phi", "delta", "kappa", "rho",
"varphi", "epsilon", "lambda", "varrho", "chi", "varepsilon",
"mu", "sigma", "psi", "zeta", "nu", "varsigma", "omega", "eta",
"xi", "Gamma", "Lambda", "Sigma", "Psi", "Delta", "Xi",
"Upsilon", "Omega", "Theta", "Pi", "Phi"
)
greek_list <- set_names(paste0("\\", greek), greek)
greek_env <- as_environment(greek_list)
## 3.4 Known symbols
latex_env <- function(expr) {
greek_env
}
to_math(pi)
to_math(beta)
## 3.5 Unknown symbols (helpers added from the source)
expr_type <- function(x) {
if (rlang::is_syntactic_literal(x)) {
"constant"
} else if (is.symbol(x)) {
"symbol"
} else if (is.call(x)) {
"call"
} else if (is.pairlist(x)) {
"pairlist"
} else {
typeof(x)
}
}
switch_expr <- function(x, ...) {
switch(expr_type(x),
...,
stop("Don't know how to handle type ",
typeof(x), call. = FALSE)
)
}
flat_map_chr <- function(.x, .f, ...) {
purrr::flatten_chr(purrr::map(.x, .f, ...))
}
all_names_rec <- function(x) {
switch_expr(x,
constant = character(),
symbol = as.character(x),
call = flat_map_chr(as.list(x[-1]), all_names)
)
}
all_names <- function(x) {
unique(all_names_rec(x))
}
all_names(expr(x + y + f(a, b, c, 10)))
latex_env <- function(expr) {
names <- all_names(expr)
symbol_env <- as_environment(set_names(names))
symbol_env
}
to_math(x)
to_math(longvariablename)
to_math(pi)
latex_env <- function(expr) {
# Unknown symbols
names <- all_names(expr)
symbol_env <- as_environment(set_names(names))
# Known symbols
env_clone(greek_env, parent = symbol_env)
}
to_math(x)
to_math(longvariablename)
to_math(pi)
# 3.6 Known functions
unary_op <- function(left, right) {
new_function(
exprs(e1 = ),
expr(
paste0(!!left, e1, !!right)
),
caller_env()
)
}
binary_op <- function(sep) {
new_function(
exprs(e1 = , e2 = ),
expr(
paste0(e1, !!sep, e2)
),
caller_env()
)
}
unary_op("\\sqrt{", "}")
binary_op("+")
# Binary operators
f_env <- child_env(
.parent = empty_env(),
`+` = binary_op(" + "),
`-` = binary_op(" - "),
`*` = binary_op(" * "),
`/` = binary_op(" / "),
`^` = binary_op("^"),
`[` = binary_op("_"),
# Grouping
`{` = unary_op("\\left{ ", " \\right}"),
`(` = unary_op("\\left( ", " \\right)"),
paste = paste,
# Other math functions
sqrt = unary_op("\\sqrt{", "}"),
sin = unary_op("\\sin(", ")"),
log = unary_op("\\log(", ")"),
abs = unary_op("\\left| ", "\\right| "),
frac = function(a, b) {
paste0("\\frac{", a, "}{", b, "}")
},
# Labelling
hat = unary_op("\\hat{", "}"),
tilde = unary_op("\\tilde{", "}")
)
latex_env <- function(expr) {
# Known functions
f_env
# Default symbols
names <- all_names(expr)
symbol_env <- as_environment(set_names(names), parent = f_env)
# Known symbols
greek_env <- env_clone(greek_env, parent = symbol_env)
greek_env
}
to_math(sin(x + pi))
to_math(log(x[i]^2))
to_math(sin(sin))
# 3.7 Unknown functions
all_calls_rec <- function(x) {
switch_expr(x,
constant = ,
symbol = character(),
call = {
fname <- as.character(x[[1]])
children <- flat_map_chr(as.list(x[-1]), all_calls)
c(fname, children)
}
)
}
all_calls <- function(x) {
unique(all_calls_rec(x))
}
all_calls(expr(f(g + b, c, d(a))))
unknown_op <- function(op) {
new_function(
exprs(... = ),
expr({
contents <- paste(..., collapse = ", ")
paste0(!!paste0("\\mathrm{", op, "}("), contents, ")")
})
)
}
unknown_op("foo")
latex_env <- function(expr) {
calls <- all_calls(expr)
call_list <- map(set_names(calls), unknown_op)
call_env <- as_environment(call_list)
# Known functions
f_env <- env_clone(f_env, call_env)
# Default symbols
names <- all_names(expr)
symbol_env <- as_environment(set_names(names), parent = f_env)
# Known symbols
greek_env <- env_clone(greek_env, parent = symbol_env)
greek_env
}
to_math(sin(pi) + f(a))
```
To adjust this behaviour, we need an escape function with methods for the `character` and `advr_latex` classes.
(Note that we must first repeat the underlying code from *Advanced R*. However, since this would be a bit verbose, and not very meaningful, we will not show this step here.)
```{r}
escape_latex <- function(x) UseMethod("escape_latex")
escape_latex.character <- function(x) {
x <- gsub("^\\\\$", "\\\\\\\\", x)
x <- gsub("^\\$$", "\\\\$", x)
x <- gsub("^\\%$", "\\\\%", x)
latex(x)
}
escape_latex.advr_latex <- function(x) x
```
We apply `escape_latex()` within `latex_env()` when creating environments for unknown symbols and unknown functions. For the unknown function, we need to modify `unknown_op()` first.
```{r}
unknown_op <- function(op) {
new_function(
exprs(... = ),
expr({
contents <- paste(..., collapse = ", ")
paste0(
!!paste0("\\mathrm{", escape_latex(op), "}("), contents, ")"
)
})
)
}
latex_env <- function(expr) {
calls <- all_calls(expr)
call_list <- map(set_names(calls), unknown_op)
call_env <- as_environment(call_list)
# Known functions
f_env <- env_clone(f_env, call_env)
# Default symbols
names <- all_names(expr)
symbol_env <- as_environment(set_names(escape_latex(names), names),
parent = f_env)
# Known symbols
greek_env <- env_clone(greek_env, parent = symbol_env)
greek_env
}
```
Now, we can validate `to_math()` on the test cases from above.
```{r}
to_math(`$`)
to_math(a$b)
to_math(`\\`)
to_math(`%`)
```
__[Q2]{.Q}__: Complete the DSL to support all the functions that `plotmath` supports.
__[A]{.solved}__: You can see all supported functions in `?plotmath`. There are a lot (!) so here we choose to implement a representative sample:
```{r, eval = FALSE}
to_math(x %+-% y)
to_math(x %*% y)
to_math(x %->% y)
to_math(bold(x))
to_math(x != y)
```
Implementing the rest is just a mechanical application of the same principles with more LaTex expressions, which can be found on [Wikipedia](https://en.wikipedia.org/wiki/Help:Displaying_a_formula).
To provide these translations, we'll follow the LaTeX section from *Advanced R* from the beginning. This makes it easier to keep an overview, as we just need to insert the specific changes at the relevant parts.
Let's start and repeat the converter function `to_math()` from the textbook.
```{r}
to_math <- function(x) {
expr <- enexpr(x)
out <- eval_bare(expr, latex_env(expr))
latex(out)
}
latex <- function(x) structure(x, class = "advr_latex")
print.advr_latex <- function(x) {
cat("<LATEX> ", x, "\n", sep = "")
}
```
One specific property in this setting is that the environment where `to_math()` evaluates the expression is not constant, but depends on what we already know about the expression.
Next, we start building up `latex_env()`, which contains a chain of all the necessary environments which `to_math()` checks to evaluate the expression in.
The first environment is the one for Greek letters.
```{r}
greek <- c(
"alpha", "theta", "tau", "beta", "vartheta", "pi", "upsilon",
"gamma", "varpi", "phi", "delta", "kappa", "rho",
"varphi", "epsilon", "lambda", "varrho", "chi", "varepsilon",
"mu", "sigma", "psi", "zeta", "nu", "varsigma", "omega", "eta",
"xi", "Gamma", "Lambda", "Sigma", "Psi", "Delta", "Xi",
"Upsilon", "Omega", "Theta", "Pi", "Phi"
)
greek_list <- set_names(paste0("\\", greek), greek)
greek_env <- as_environment(greek_list)
latex_env <- function(expr) {
greek_env
}
```
We already know from *Advanced R* that e.g. `to_math(pi)` now correctly converts to `\\pi`. So, let's move on to the next one.
Here, it'll become a bit more technical. Not every symbol is Greek (and not every part of an expression is a symbol). To find out which symbols are present within the expression, first, we use an approach from [section 5 of the expressions chapter](https://adv-r.hadley.nz/expressions.html#ast-funs) (walking the AST to find all symbols) where Hadley recursively walks the AST to distinguish between different expression element types.
Let's briefly repeat the helpers defined in that section:
```{r}
expr_type <- function(x) {
if (rlang::is_syntactic_literal(x)) {
"constant"
} else if (is.symbol(x)) {
"symbol"
} else if (is.call(x)) {
"call"
} else if (is.pairlist(x)) {
"pairlist"
} else {
typeof(x)
}
}
switch_expr <- function(x, ...) {
switch(expr_type(x),
...,
stop("Don't know how to handle type ",
typeof(x), call. = FALSE)
)
}
flat_map_chr <- function(.x, .f, ...) {
purrr::flatten_chr(purrr::map(.x, .f, ...))
}
```
This lets us define `all_names()`, which returns the desired symbols, already converted to characters.
```{r}
all_names_rec <- function(x) {
switch_expr(x,
constant = character(),
symbol = as.character(x),
call = flat_map_chr(as.list(x[-1]), all_names)
)
}
all_names <- function(x) {
unique(all_names_rec(x))
}
all_names(expr(x + y + f(a, b, c, 10)))
```
We use `all_names()` now within `latex_env()` to create an environment of the symbols which were found within the expression. This environment will be set as the parent environment of `greek_env`.
```{r}
latex_env <- function(expr) {
# Unknown symbols
names <- all_names(expr)
symbol_env <- as_environment(set_names(names))
# Known symbols
env_clone(greek_env, parent = symbol_env)
}
```
In this way, `to_math()` will first convert all known Greek letters (found in `greek_env`) and then any other symbols, which are left as is (in this implementation).
We also have to add support for functions. This will give us the opportunity to insert some specific support for `plotmath` functions.
To support a whole bunch of unary and binary functions within the function environment (`f_env`), which will be added next to `latex_env`, Hadley defines the following two helpers in *Advanced R*.
```{r}
unary_op <- function(left, right) {
new_function(
exprs(e1 = ),
expr(
paste0(!!left, e1, !!right)
),
caller_env()
)
}
binary_op <- function(sep) {
new_function(
exprs(e1 = , e2 = ),
expr(
paste0(e1, !!sep, e2)
),
caller_env()
)
}
```
While defining the function environment, `f_env`, we mostly continue to copy the exact code from *Advanced R*. However, at the bottom we add a short section where we define some extra conversions which are part of `plotmath` (and selected above in our intro to this solution).
```{r}
f_env <- child_env(
# Binary operators
.parent = empty_env(),
`+` = binary_op(" + "),
`-` = binary_op(" - "),
`*` = binary_op(" * "),
`/` = binary_op(" / "),
`^` = binary_op("^"),
`[` = binary_op("_"),
# Grouping
`{` = unary_op("\\left{ ", " \\right}"),
`(` = unary_op("\\left( ", " \\right)"),
paste = paste,
# Other math functions
sqrt = unary_op("\\sqrt{", "}"),
sin = unary_op("\\sin(", ")"),
log = unary_op("\\log(", ")"),
abs = unary_op("\\left| ", "\\right| "),
frac = function(a, b) {
paste0("\\frac{", a, "}{", b, "}")
},
# Labelling
hat = unary_op("\\hat{", "}"),
tilde = unary_op("\\tilde{", "}"),
# Plotmath
`%+-%` = binary_op(" \\pm "),
`%*%` = binary_op(" \\times "),
`%->%` = binary_op(" \\rightarrow "),
bold = unary_op("\\textbf{", "}"),
`!=` = binary_op(" \\neq ")
)
```
Again we extend `latex_env()` to include the additional environment, `f_env`, which must be the parent of the symbol environment (which is the parent of the Greek symbol environment).
```{r}
latex_env <- function(expr) {
# Known functions
f_env
# Default symbols
names <- all_names(expr)
symbol_env <- as_environment(set_names(names), parent = f_env)
# Known symbols
greek_env <- env_clone(greek_env, parent = symbol_env)
greek_env
}
```
Now, we can finally check if our new functionality works:
```{r}
# New plotmath functionality
to_math(x %+-% y)