bookclub-advr

DSLC Advanced R Book Club
git clone https://git.eamoncaddigan.net/bookclub-advr.git
Log | Files | Refs | README | LICENSE

html.json (32880B)


      1 {
      2   "hash": "8eddf7bc07df6df9746c96fcb4301db8",
      3   "result": {
      4     "engine": "knitr",
      5     "markdown": "---\nengine: knitr\ntitle: Expressions\n---\n\n## Learning objectives:\n\n* Understand the idea of the abstract syntax tree (AST). \n* Discuss the data structures that underlie the AST:\n  * Constants\n  * Symbols\n  * Calls\n* Explore the idea behind parsing.\n* Explore some details of R's grammar.\n* Discuss the use or recursive functions to compute on the language.\n* Work with three other more specialized data structures:\n  * Pairlists\n  * Missing arguments\n  * Expression vectors\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rlang)\nlibrary(lobstr)\n```\n:::\n\n\n## Introduction\n\n> To compute on the language, we first need to understand its structure.\n\n* This requires a few things:\n  * New vocabulary.\n  * New tools to inspect and modify expressions.\n  * Approach the use of the language with new ways of thinking.\n* One of the first new ways of thinking is the distinction between an operation and its result.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ny <- x * 10\n```\n\n::: {.cell-output .cell-output-error}\n\n```\n#> Error: object 'x' not found\n```\n\n\n:::\n:::\n\n\n* We can capture the intent of the code without executing it using the rlang package.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nz <- rlang::expr(y <- x * 10)\n\nz\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> y <- x * 10\n```\n\n\n:::\n:::\n\n\n* We can then evaluate the expression using the **base::eval** function.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- 4\n\nbase::eval(expr(y <- x * 10))\n\ny\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 40\n```\n\n\n:::\n:::\n\n\n### Evaluating multiple expressions \n\n* The function `expression()` allows for multiple expressions, and in some ways it acts similarly to the way files are `source()`d in.  That is, we `eval()`uate all of the expressions at once.\n\n* `expression()` returns a vector and can be passed to `eval()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nz <- expression(x <- 4, x * 10)\n\neval(z)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 40\n```\n\n\n:::\n\n```{.r .cell-code}\nis.atomic(z)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] FALSE\n```\n\n\n:::\n\n```{.r .cell-code}\nis.vector(z)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n* `exprs()` does not evaluate everything at once.  To evaluate each expression, the individual expressions must be evaluated in a loop.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nfor (i in exprs(x <- 4, x * 10)) {\nprint(i)\nprint(eval(i))\n}\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> x <- 4\n#> [1] 4\n#> x * 10\n#> [1] 40\n```\n\n\n:::\n:::\n\n\n## Abstract Syntax Tree (AST)\n\n* Expressions are objects that capture the structure of code without evaluating it.\n* Expressions are also called abstract syntax trees (ASTs) because the structure of code is hierarchical and can be naturally represented as a tree. \n* Understanding this tree structure is crucial for inspecting and modifying expressions.\n  * Branches = Calls\n  * Leaves = Symbols and constants\n\n\n::: {.cell}\n\n```{.r .cell-code}\nf(x, \"y\", 1)\n```\n:::\n\n\n![](images/simple.png)\n\n### With `lobstr::ast():`\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(f(x, \"y\", 1))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─f \n#> ├─x \n#> ├─\"y\" \n#> └─1\n```\n\n\n:::\n:::\n\n\n* Some functions might also contain more calls like the example below:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nf(g(1, 2), h(3, 4, i())):\n```\n:::\n\n![](images/complicated.png)\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(f(g(1, 2), h(3, 4, i())))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─f \n#> ├─█─g \n#> │ ├─1 \n#> │ └─2 \n#> └─█─h \n#>   ├─3 \n#>   ├─4 \n#>   └─█─i\n```\n\n\n:::\n:::\n\n* Read the **hand-drawn diagrams** from left-to-right (ignoring vertical position)\n* Read the **lobstr-drawn diagrams** from top-to-bottom (ignoring horizontal position).\n* The depth within the tree is determined by the nesting of function calls. \n* Depth also determines evaluation order, **as evaluation generally proceeds from deepest-to-shallowest, but this is not guaranteed because of lazy evaluation**.\n\n###  Infix calls\n\n> Every call in R can be written in tree form because any call can be written in prefix form.\n\nAn infix operator is a function where the function name is placed between its arguments. Prefix form is when then function name comes before the arguments, which are enclosed in parentheses. [Note that the name infix comes from the words prefix and suffix.]\n\n\n::: {.cell}\n\n```{.r .cell-code}\ny <- x * 10\n`<-`(y, `*`(x, 10))\n```\n:::\n\n\n* A characteristic of the language is that infix functions can always be written as prefix functions; therefore, all function calls can be represented using an AST.\n\n![](images/prefix.png)\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(y <- x * 10)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`<-` \n#> ├─y \n#> └─█─`*` \n#>   ├─x \n#>   └─10\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(`<-`(y, `*`(x, 10)))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`<-` \n#> ├─y \n#> └─█─`*` \n#>   ├─x \n#>   └─10\n```\n\n\n:::\n:::\n\n\n* There is no difference between the ASTs for the infix version vs the prefix version, and if you generate an expression with prefix calls, R will still print it in infix form:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nrlang::expr(`<-`(y, `*`(x, 10)))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> y <- x * 10\n```\n\n\n:::\n:::\n\n\n## Expression \n\n* Collectively, the data structures present in the AST are called expressions.\n* These include:\n  1. Constants\n  2. Symbols\n  3. Calls \n  4. Pairlists\n\n### Constants\n\n* Scalar constants are the simplest component of the AST. \n* A constant is either **NULL** or a **length-1** atomic vector (or scalar) \n  * e.g., `TRUE`, `1L`, `2.5`, `\"x\"`, or `\"hello\"`. \n* We can test for a constant with `rlang::is_syntactic_literal()`.\n* Constants are self-quoting in the sense that the expression used to represent a constant is the same constant:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nidentical(expr(TRUE), TRUE)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nidentical(expr(1), 1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nidentical(expr(2L), 2L)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nidentical(expr(\"x\"), \"x\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nidentical(expr(\"hello\"), \"hello\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n### Symbols\n\n* A symbol represents the name of an object.\n  * `x`\n  * `mtcars`\n  * `mean`\n* In base R, the terms symbol and name are used interchangeably (i.e., `is.name()` is identical to `is.symbol()`), but this book used symbol consistently because **\"name\"** has many other meanings.\n* You can create a symbol in two ways: \n  1. by capturing code that references an object with `expr()`.\n  2. turning a string into a symbol with `rlang::sym()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexpr(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> x\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsym(\"x\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> x\n```\n\n\n:::\n:::\n\n\n* A symbol can be turned back into a string with `as.character()` or `rlang::as_string()`. \n* `as_string()` has the advantage of clearly signalling that you’ll get a character vector of length 1.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nas_string(expr(x))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"x\"\n```\n\n\n:::\n:::\n\n\n* We can recognize a symbol because it is printed without quotes\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexpr(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> x\n```\n\n\n:::\n:::\n\n\n* `str()` tells you that it is a symbol, and `is.symbol()` is TRUE:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nstr(expr(x))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#>  symbol x\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nis.symbol(expr(x))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n* The symbol type is not vectorised, i.e., a symbol is always length 1. \n* If you want multiple symbols, you’ll need to put them in a list, using `rlang::syms()`.\n\nNote that `as_string()` will not work on expressions which are not symbols.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nas_string(expr(x+y))\n```\n\n::: {.cell-output .cell-output-error}\n\n```\n#> Error in `as_string()`:\n#> ! Can't convert a call to a string.\n```\n\n\n:::\n:::\n\n\n\n### Calls\n\n* A call object represents a captured function call. \n* Call objects are a special type of list. \n  * The first component specifies the function to call (usually a symbol, i.e., the name fo the function). \n  * The remaining elements are the arguments for that call. \n* Call objects create branches in the AST, because calls can be nested inside other calls.\n* You can identify a call object when printed because it looks just like a function call. \n* Confusingly `typeof()` and `str()` print language for call objects (where we might expect it to return that it is a \"call\" object), but `is.call()` returns TRUE:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(read.table(\"important.csv\", row.names = FALSE))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─read.table \n#> ├─\"important.csv\" \n#> └─row.names = FALSE\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- expr(read.table(\"important.csv\", row.names = FALSE))\n```\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\ntypeof(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"language\"\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nis.call(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n### Subsetting\n\n* Calls generally behave like lists.\n* Since they are list-like, you can use standard subsetting tools. \n* The first element of the call object is the function to call, which is usually a symbol:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx[[1]]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> read.table\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nis.symbol(x[[1]])\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n* The remainder of the elements are the arguments:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nis.symbol(x[-1])\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] FALSE\n```\n\n\n:::\n\n```{.r .cell-code}\nas.list(x[-1])\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [[1]]\n#> [1] \"important.csv\"\n#> \n#> $row.names\n#> [1] FALSE\n```\n\n\n:::\n:::\n\n* We can extract individual arguments with [[ or, if named, $:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx[[2]]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"important.csv\"\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx$row.names\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] FALSE\n```\n\n\n:::\n:::\n\n\n* We can determine the number of arguments in a call object by subtracting 1 from its length:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlength(x) - 1\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 2\n```\n\n\n:::\n:::\n\n\n* Extracting specific arguments from calls is challenging because of R’s flexible rules for argument matching:\n  * It could potentially be in any location, with the full name, with an abbreviated name, or with no name. \n\n* To work around this problem, you can use `rlang::call_standardise()` which standardizes all arguments to use the full name:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nrlang::call_standardise(x)\n```\n\n::: {.cell-output .cell-output-stderr}\n\n```\n#> Warning: `call_standardise()` is deprecated as of rlang 0.4.11\n#> This warning is displayed once every 8 hours.\n```\n\n\n:::\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> read.table(file = \"important.csv\", row.names = FALSE)\n```\n\n\n:::\n:::\n\n\n* But If the function uses ... it’s not possible to standardise all arguments.\n* Calls can be modified in the same way as lists:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx$header <- TRUE\nx\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> read.table(\"important.csv\", row.names = FALSE, header = TRUE)\n```\n\n\n:::\n:::\n\n\n### Function position\n\n* The first element of the call object is the function position. This contains the function that will be called when the object is evaluated, and is usually a symbol.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(foo())\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─foo\n```\n\n\n:::\n:::\n\n\n* While R allows you to surround the name of the function with quotes, the parser converts it to a symbol:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(\"foo\"())\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─foo\n```\n\n\n:::\n:::\n\n\n* However, sometimes the function doesn’t exist in the current environment and you need to do some computation to retrieve it: \n  * For example, if the function is in another package, is a method of an R6 object, or is created by a function factory. In this case, the function position will be occupied by another call:\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(pkg::foo(1))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─█─`::` \n#> │ ├─pkg \n#> │ └─foo \n#> └─1\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(obj$foo(1))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─█─`$` \n#> │ ├─obj \n#> │ └─foo \n#> └─1\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(foo(1)(2))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─█─foo \n#> │ └─1 \n#> └─2\n```\n\n\n:::\n:::\n\n\n![](images/call-call.png)\n\n### Constructing\n\n* You can construct a call object from its components using `rlang::call2()`. \n* The first argument is the name of the function to call (either as a string, a symbol, or another call).\n* The remaining arguments will be passed along to the call:\n\n\n::: {.cell}\n\n```{.r .cell-code}\ncall2(\"mean\", x = expr(x), na.rm = TRUE)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> mean(x = x, na.rm = TRUE)\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\ncall2(expr(base::mean), x = expr(x), na.rm = TRUE)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> base::mean(x = x, na.rm = TRUE)\n```\n\n\n:::\n:::\n\n\n* Infix calls created in this way still print as usual.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ncall2(\"<-\", expr(x), 10)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> x <- 10\n```\n\n\n:::\n:::\n\n\n## Parsing and grammar\n\n* **Parsing** - The process by which a computer language takes a string and constructs an expression. Parsing is governed by a set of rules known as a grammar. \n* We are going to use `lobstr::ast()` to explore some of the details of R’s grammar, and then show how you can transform back and forth between expressions and strings.\n* **Operator precedence** - Conventions used by the programming language to resolve ambiguity.\n* Infix functions introduce two sources of ambiguity.\n* The first source of ambiguity arises from infix functions: what does 1 + 2 * 3 yield? Do you get 9 (i.e., (1 + 2) * 3), or 7 (i.e., 1 + (2 * 3))? In other words, which of the two possible parse trees below does R use?\n\n![](images/ambig-order.png)\n\n* Programming languages use conventions called operator precedence to resolve this ambiguity. We can use `ast()` to see what R does:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(1 + 2 * 3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`+` \n#> ├─1 \n#> └─█─`*` \n#>   ├─2 \n#>   └─3\n```\n\n\n:::\n:::\n\n\n* PEMDAS (or BEDMAS or BODMAS, depending on where in the world you grew up) is pretty clear on what to do. Other operator precedence isn't as clear. \n* There’s one particularly surprising case in R: \n  * ! has a much lower precedence (i.e., it binds less tightly) than you might expect. \n  * This allows you to write useful operations like:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(!x %in% y)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`!` \n#> └─█─`%in%` \n#>   ├─x \n#>   └─y\n```\n\n\n:::\n:::\n\n* **R has over 30 infix operators divided into 18 precedence** groups. \n* While the details are described in `?Syntax`, very few people have memorized the complete ordering.\n* If there’s any confusion, use parentheses!\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# override PEMDAS\nlobstr::ast((1 + 2) * 3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`*` \n#> ├─█─`(` \n#> │ └─█─`+` \n#> │   ├─1 \n#> │   └─2 \n#> └─3\n```\n\n\n:::\n:::\n\n\n### Associativity\n\n* The second source of ambiguity is introduced by repeated usage of the same infix function. \n\n\n::: {.cell}\n\n```{.r .cell-code}\n1 + 2 + 3\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 6\n```\n\n\n:::\n\n```{.r .cell-code}\n# What does R do first?\n(1 + 2) + 3\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 6\n```\n\n\n:::\n\n```{.r .cell-code}\n# or\n1 + (2 + 3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 6\n```\n\n\n:::\n:::\n\n\n* In this case it doesn't matter. Other places it might, like in `ggplot2`. \n\n* In R, most operators are left-associative, i.e., the operations on the left are evaluated first:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(1 + 2 + 3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`+` \n#> ├─█─`+` \n#> │ ├─1 \n#> │ └─2 \n#> └─3\n```\n\n\n:::\n:::\n\n\n* There are two exceptions to the left-associative rule:\n  1. exponentiation\n  2. assignment\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(2 ^ 2 ^ 3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`^` \n#> ├─2 \n#> └─█─`^` \n#>   ├─2 \n#>   └─3\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlobstr::ast(x <- y <- z)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`<-` \n#> ├─x \n#> └─█─`<-` \n#>   ├─y \n#>   └─z\n```\n\n\n:::\n:::\n\n\n### Parsing and deparsing\n\n* Parsing - turning characters you've typed into an AST (i.e., from strings to expressions).\n* R usually takes care of parsing code for us. \n* But occasionally you have code stored as a string, and you want to parse it yourself. \n* You can do so using `rlang::parse_expr()`:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx1 <- \"y <- x + 10\"\nx1\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"y <- x + 10\"\n```\n\n\n:::\n\n```{.r .cell-code}\nis.call(x1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] FALSE\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx2 <- rlang::parse_expr(x1)\nx2\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> y <- x + 10\n```\n\n\n:::\n\n```{.r .cell-code}\nis.call(x2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n* `parse_expr()` always returns a single expression.\n* If you have multiple expression separated by `;` or `,`, you’ll need to use `rlang::parse_exprs()` which is the plural version of `rlang::parse_expr()`. It returns a list of expressions:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx3 <- \"a <- 1; a + 1\"\n```\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nrlang::parse_exprs(x3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [[1]]\n#> a <- 1\n#> \n#> [[2]]\n#> a + 1\n```\n\n\n:::\n:::\n\n\n* If you find yourself parsing strings into expressions often, **quasiquotation** may be a safer approach.\n  * More about quasiquaotation in Chapter 19.\n* The inverse of parsing is deparsing.\n* **Deparsing** - given an expression, you want the string that would generate it. \n* Deparsing happens automatically when you print an expression.\n* You can get the string with `rlang::expr_text()`:\n* Parsing and deparsing are not symmetric.\n  * Parsing creates the AST which means that we lose backticks around ordinary names, comments, and whitespace.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ncat(expr_text(expr({\n  # This is a comment\n  x <-             `x` + 1\n})))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> {\n#>     x <- x + 1\n#> }\n```\n\n\n:::\n:::\n\n\n## Using the AST to solve more complicated problems\n\n* Here we focus on what we learned to perform recursion on the AST.\n* Two parts of a recursive function:\n  * Recursive case: handles the nodes in the tree. Typically, you’ll do something to each child of a node, usually calling the recursive function again, and then combine the results back together again. For expressions, you’ll need to handle calls and pairlists (function arguments).\n  * Base case: handles the leaves of the tree. The base cases ensure that the function eventually terminates, by solving the simplest cases directly. For expressions, you need to handle symbols and constants in the base case.\n\n\n### Two helper functions\n\n* First, we need an `epxr_type()` function to return the type of expression element as a string.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexpr_type <- function(x) {\n  if (rlang::is_syntactic_literal(x)) {\n    \"constant\"\n  } else if (is.symbol(x)) {\n    \"symbol\"\n  } else if (is.call(x)) {\n    \"call\"\n  } else if (is.pairlist(x)) {\n    \"pairlist\"\n  } else {\n    typeof(x)\n  }\n}\n```\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexpr_type(expr(\"a\"))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"constant\"\n```\n\n\n:::\n\n```{.r .cell-code}\nexpr_type(expr(x))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"symbol\"\n```\n\n\n:::\n\n```{.r .cell-code}\nexpr_type(expr(f(1, 2)))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"call\"\n```\n\n\n:::\n:::\n\n\n* Second, we need a wrapper function to handle exceptions.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nswitch_expr <- function(x, ...) {\n  switch(expr_type(x),\n    ...,\n    stop(\"Don't know how to handle type \", typeof(x), call. = FALSE)\n  )\n}\n```\n:::\n\n\n* Lastly, we can write a basic template that walks the AST using the `switch()` statement.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nrecurse_call <- function(x) {\n  switch_expr(x,\n    # Base cases\n    symbol = ,\n    constant = ,\n\n    # Recursive cases\n    call = ,\n    pairlist =\n  )\n}\n```\n:::\n\n\n### Specific use cases for `recurse_call()`\n\n### Example 1: Finding F and T\n\n* Using `F` and `T` in our code rather than `FALSE` and `TRUE` is bad practice.\n* Say we want to walk the AST to find times when we use `F` and `T`.\n* Start off by finding the type of `T` vs `TRUE`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexpr_type(expr(TRUE))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"constant\"\n```\n\n\n:::\n\n```{.r .cell-code}\nexpr_type(expr(T))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"symbol\"\n```\n\n\n:::\n:::\n\n\n* With this knowledge, we can now write the base cases of our recursive function.\n* The logic is as follows:\n  * A constant is never a logical abbreviation and a symbol is an abbreviation if it is \"F\" or \"T\":\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlogical_abbr_rec <- function(x) {\n  switch_expr(x,\n    constant = FALSE,\n    symbol = as_string(x) %in% c(\"F\", \"T\")\n  )\n}\n```\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlogical_abbr_rec(expr(TRUE))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] FALSE\n```\n\n\n:::\n\n```{.r .cell-code}\nlogical_abbr_rec(expr(T))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n* It's best practice to write another wrapper, assuming every input you receive will be an expression.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlogical_abbr <- function(x) {\n  logical_abbr_rec(enexpr(x))\n}\n\nlogical_abbr(T)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nlogical_abbr(FALSE)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] FALSE\n```\n\n\n:::\n:::\n\n\n#### Next step: code for the recursive cases\n\n* Here we want to do the same thing for calls and for pairlists.\n* Here's the logic: recursively apply the function to each subcomponent, and return `TRUE` if any subcomponent contains a logical abbreviation.\n* This is simplified by using the `purrr::some()` function, which iterates over a list and returns `TRUE` if the predicate function is true for any element.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlogical_abbr_rec <- function(x) {\n  switch_expr(x,\n  # Base cases\n  constant = FALSE,\n  symbol = as_string(x) %in% c(\"F\", \"T\"),\n  # Recursive cases\n  call = ,\n  # Are we sure this is the correct function to use?\n  # Why not logical_abbr_rec?\n  pairlist = purrr::some(x, logical_abbr_rec)\n  )\n}\n\nlogical_abbr(mean(x, na.rm = T))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nlogical_abbr(function(x, na.rm = T) FALSE)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n### Example 2: Finding all variables created by assignment\n\n* Listing all the variables is a little more complicated. \n* Figure out what assignment looks like based on the AST.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nast(x <- 10)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> █─`<-` \n#> ├─x \n#> └─10\n```\n\n\n:::\n:::\n\n\n* Now we need to decide what data structure we're going to use for the results.\n  * Easiest thing will be to return a character vector.\n  * We would need to use a list if we wanted to return symbols.\n\n### Dealing with the base cases\n\n\n::: {.cell}\n\n```{.r .cell-code}\nfind_assign_rec <- function(x) {\n  switch_expr(x,\n    constant = ,\n    symbol = character()\n  )\n}\nfind_assign <- function(x) find_assign_rec(enexpr(x))\n\nfind_assign(\"x\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> character(0)\n```\n\n\n:::\n\n```{.r .cell-code}\nfind_assign(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> character(0)\n```\n\n\n:::\n:::\n\n\n### Dealing with the recursive cases\n\n* Here is the function to flatten pairlists.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nflat_map_chr <- function(.x, .f, ...) {\n  purrr::flatten_chr(purrr::map(.x, .f, ...))\n}\n\nflat_map_chr(letters[1:3], ~ rep(., sample(3, 1)))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"a\" \"a\" \"b\" \"b\" \"c\" \"c\"\n```\n\n\n:::\n:::\n\n\n* Here is the code needed to identify calls.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nfind_assign_rec <- function(x) {\n  switch_expr(x,\n    # Base cases\n    constant = ,\n    symbol = character(),\n\n    # Recursive cases\n    pairlist = flat_map_chr(as.list(x), find_assign_rec),\n    call = {\n      if (is_call(x, \"<-\")) {\n        as_string(x[[2]])\n      } else {\n        flat_map_chr(as.list(x), find_assign_rec)\n      }\n    }\n  )\n}\n\nfind_assign(a <- 1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"a\"\n```\n\n\n:::\n\n```{.r .cell-code}\nfind_assign({\n  a <- 1\n  {\n    b <- 2\n  }\n})\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"a\" \"b\"\n```\n\n\n:::\n:::\n\n\n### Make the function more robust\n\n* Throw cases at it that we think might break the function. \n* Write a function to handle these cases.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nfind_assign_call <- function(x) {\n  if (is_call(x, \"<-\") && is_symbol(x[[2]])) {\n    lhs <- as_string(x[[2]])\n    children <- as.list(x)[-1]\n  } else {\n    lhs <- character()\n    children <- as.list(x)\n  }\n\n  c(lhs, flat_map_chr(children, find_assign_rec))\n}\n\nfind_assign_rec <- function(x) {\n  switch_expr(x,\n    # Base cases\n    constant = ,\n    symbol = character(),\n\n    # Recursive cases\n    pairlist = flat_map_chr(x, find_assign_rec),\n    call = find_assign_call(x)\n  )\n}\n\nfind_assign(a <- b <- c <- 1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"a\" \"b\" \"c\"\n```\n\n\n:::\n\n```{.r .cell-code}\nfind_assign(system.time(x <- print(y <- 5)))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"x\" \"y\"\n```\n\n\n:::\n:::\n\n\n* This approach certainly is more complicated, but it's important to start simple and move up.\n\n## Specialised data structures\n\n* Pairlists\n* Missing arguments \n* Expression vectors\n\n###  Pairlists\n\n* Pairlists are a remnant of R’s past and have been replaced by lists almost everywhere. \n* The only place you are likely to see pairlists in R is when working with calls to the function, as the formal arguments to a function are stored in a pairlist:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nf <- expr(function(x, y = 10) x + y)\n```\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nargs <- f[[2]]\nargs\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> $x\n#> \n#> \n#> $y\n#> [1] 10\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\ntypeof(args)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"pairlist\"\n```\n\n\n:::\n:::\n\n* Fortunately, whenever you encounter a pairlist, you can treat it just like a regular list:\n\n\n::: {.cell}\n\n```{.r .cell-code}\npl <- pairlist(x = 1, y = 2)\n```\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlength(pl)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 2\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\npl$x\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 1\n```\n\n\n:::\n:::\n\n\n### Missing arguments\n\n* Empty symbols\n* To create an empty symbol, you need to use `missing_arg()` or `expr()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nmissing_arg()\n```\n\n```{.r .cell-code}\ntypeof(missing_arg())\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"symbol\"\n```\n\n\n:::\n:::\n\n\n* Empty symbols don't print anything.\n  * To check, we need to use `rlang::is_missing()`\n\n\n::: {.cell}\n\n```{.r .cell-code}\nis_missing(missing_arg())\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n* These are usually present in function formals:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nf <- expr(function(x, y = 10) x + y)\n\nargs <- f[[2]]\n\n\nis_missing(args[[1]])\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] TRUE\n```\n\n\n:::\n:::\n\n\n### Expression vectors\n\n* An expression vector is just a list of expressions.\n  * The only difference is that calling `eval()` on an expression evaluates each individual expression. \n  * Instead, it might be more advantageous to use a list of expressions.\n\n* Expression vectors are only produced by two base functions: \n  `expression()` and `parse()`:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexp1 <- parse(text = c(\" \nx <- 4\nx\n\"))\nexp1\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> expression(x <- 4, x)\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexp2 <- expression(x <- 4, x)\nexp2\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> expression(x <- 4, x)\n```\n\n\n:::\n:::\n\n\n\n::: {.cell}\n\n```{.r .cell-code}\ntypeof(exp1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"expression\"\n```\n\n\n:::\n\n```{.r .cell-code}\ntypeof(exp2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] \"expression\"\n```\n\n\n:::\n:::\n\n\n\n- Like calls and pairlists, expression vectors behave like lists:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlength(exp1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> [1] 2\n```\n\n\n:::\n\n```{.r .cell-code}\nexp1[[1]]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n#> x <- 4\n```\n\n\n:::\n:::\n\n",
      6     "supporting": [
      7       "18_files"
      8     ],
      9     "filters": [
     10       "rmarkdown/pagebreak.lua"
     11     ],
     12     "includes": {},
     13     "engineDependencies": {},
     14     "preserve": {},
     15     "postProcess": true
     16   }
     17 }