-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chapter_18.Rmd
376 lines (253 loc) · 6.91 KB
/
Chapter_18.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
---
title: "Chapter 18"
author: "Julin Maloof"
date: "2023-07-07"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(rlang)
library(lobstr)
```
# Expressions
## 18.1 Intro
Need to capture the intent of code without running it. This is what an expression is.
```{r}
z <- rlang::expr(y <- x * 10)
z
#> y <- x * 10
```
An expression is an object that captures the structure of the code.
You can evaluate an expression (run it) using `eval()`
```{r}
x <- 4
eval(z)
y
```
## 18.2 Abstract Structure Trees
Expressions are also called abstract syntax trees (ASTs)
```{r}
ast(f(x, "y", 1))
```
```{r}
lobstr::ast(f(g(1, 2), h(3, 4, i())))
```
### 18.2.4 Exercises
#### 1. Reconstruct the code from the ASTs:
`f(g,h)`
`3 + 1 + 2`
`(x+y) * z`
#### 2. Draw and check
```{r}
ast(f(g(h(i(1, 2, 3)))))
ast(f(1, g(2, h(3, i()))))
```
#### 3. What is happening with these trees?
infix functions.
#### 4. What is special about the AST below? (Hint: re-read Section 6.2.1.)
```{r}
lobstr::ast(function(x = 1, y = 2) {})
```
#### 5. What does the call tree of an if statement with multiple else if conditions look like? Why?
```{r}
ast(
if(x < 10) {
c(1)
} else {
if(y <10) {
c(2)
} else {
c(3)
}
}
)
```
## 18.3 Expressions
Expressions can be constant scalars, symbols, call objects, and pairlists.
### 18.3.1 Constants
either NULL or a lengh-1 atomic vector
### 18.3.2
A symbol represents the name of an object.
Can create one two ways:
```{r}
expr(x)
sym("x")
```
can turn back in to string with:
```{r}
as_string(expr(x))
as.character(expr(x))
```
testing for a symbol
```{r}
str(expr(x))
is.symbol(expr(x))
```
### 18.3.3 Calls
A captured function call
A special type of list, where the first component specifies the function to call and the remaining elements are the arguments for that call
test with `is.call`
```{r}
x <- expr(read.table("important.csv", row.names = FALSE))
typeof(x)
is.call(x)
```
### 18.3.3.a Subsetting.
Like subsetting a list
```{r}
x[[1]]
```
```{r}
as.list(x[-1])
```
extracting individual arguments is tough because of r's flexible argument matching. Use `call_standardize` to fix this:
```{r}
rlang::call_standardise(x)
#> read.table(file = "important.csv", row.names = FALSE)
```
Can modify just like list:
```{r}
x$header <- TRUE
x
#> read.table("important.csv", row.names = FALSE, header = TRUE)
```
### 18.3.4 Exercises
#### 1 Which two of the six types of atomic vector can’t appear in an expression? Why? Similarly, why can’t you create an expression that contains an atomic vector of length greater than one?
I would guess that complex and raw cannot appear in expressions. Maybe becuase you cannot type them directly.
Same, length greater than one you can't just type out but have to have a call.
#### 2 What happens when you subset a call object to remove the first element? e.g. expr(read.csv("foo.csv", header = TRUE))[-1]. Why?
```{r}
expr(read.csv("foo.csv", header = TRUE))[-1]
```
What was the second position now becomes first and is treated as a function (because by definition the first element of a call object is the function)
#### 3. Describe the differences:
```{r}
x <- 1:10
call2(median, x, na.rm = TRUE)
print("-")
call2(expr(median), x, na.rm = TRUE)
print("-")
call2(median, expr(x), na.rm = TRUE)
print("-")
call2(expr(median), expr(x), na.rm = TRUE)
print("-")
```
Basically, encapsulating in `expr` is preventing the object from being evaluated in `call2`
#### 4. call_standardize does not well for the below. Why not? What makes mean specia?
```{r}
call_standardise(quote(mean(1:10, na.rm = TRUE)))
#> mean(x = 1:10, na.rm = TRUE)
call_standardise(quote(mean(n = T, 1:10)))
#> mean(x = 1:10, n = T)
call_standardise(quote(mean(x = 1:10, , TRUE)))
#> mean(x = 1:10, , TRUE)
```
because of `...`
#### 5. Why does this code not make sense?
```{r}
x <- expr(foo(x = 1))
names(x) <- c("x", "y")
```
Because what does it mean to name the function in the call?
#### 6. Construct the expression if(x > 1) "a" else "b" using multiple calls to call2(). How does the code structure reflect the structure of the AST?
```{r}
z <- call2("if", "x>1", "a", "b")
# doesn't seem like I need multiple calls
z
ast(if(x > 1) "a" else "b")
```
## 18.4
### 18.4.4 Exercises
#### 1. R uses parentheses in two slightly different ways as illustrated by these two calls:
```{r}
lobstr::ast(f((1)))
```
```{r}
lobstr::ast(`(`(1 + 1))
```
Compare and contrast the two uses by referencing the AST.
_I think the point is that the parentheses can be used to either determine operator precedence, or to enclose the argument list to a function_
#### 2.
= can also be used in two ways. Construct a simple example that shows both uses.
```{r}
f <- function(x=3, y=5) z=x+y
lobstr::ast(f)
lobstr::ast(function(x=3, y=5) z=x+y)
```
_= can either be used as an assignment operator, or to denote arguments to a function._
#### 3. Does -2^2 yield 4 or -4? Why?
-4 because of operator precedence
```{r}
-2^2
```
#### 4. What does !1 + !1 return? Why?
zero because !1 is FALSE
#### 5. Why does x1 <- x2 <- x3 <- 0 work? Describe the two reasons.
_assignment works from right to left and ??_
#### 6. Compare the ASTs of x + y %+% z and x ^ y %+% z. What have you learned about the precedence of custom infix functions?
```{r}
ast(x + y %+% z)
ast(x ^ y %+% z)
```
precedence over + but not ^
#### 7. What happens if you call parse_expr() with a string that generates multiple expressions? e.g. parse_expr("x + 1; y + 1")
```{r, error=TRUE}
parse_expr("x + 1; y + 1")
```
#### 8. What happens if you attempt to parse an invalid expression? e.g. "a +" or "f())".
```{r, error=TRUE}
parse_expr("x + ")
```
#### 9. deparse() produces vectors when the input is long. For example, the following call produces a vector of length two:
```{r}
expr <- expr(g(a + b + c + d + e + f + g + h + i + j + k + l +
m + n + o + p + q + r + s + t + u + v + w + x + y + z))
deparse(expr)
```
```{r}
expr_text(expr)
```
What does expr_text() do instead?
_puts in a new line_
#### 10. pairwise.t.test() assumes that deparse() always returns a length one character vector. Can you construct an input that violates this expectation? What happens?
## 18.5 Walking the AST with recursive functions
Function for base case:
```{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 function (not sure I understand this...)
```{r}
switch_expr <- function(x, ...) {
switch(expr_type(x),
...,
stop("Don't know how to handle type ", typeof(x), call. = FALSE)
)
}
```
Walk the tree
```{r}
recurse_call <- function(x) {
switch_expr(x,
# Base cases
symbol = ,
constant = ,
# Recursive cases
call = ,
pairlist =
)
}
```