14 Quasiquotation

14.1 Motivation

  1. Q: For each function in the following base R code, identify which arguments are quoted and which are evaluated.

    A:

    Some of the arguments (mtcars or mtcars2) are objects, which can be found in the global environment. When you type them into the console, the object will be returned. Others such as cyl, sum(vs) or am will need to be evaluated within a certain environment. That’s why they are quoted.

  2. Q: For each function in the following tidyverse code, identify which arguments are quoted and which are evaluated.

    A:

    The column names in piped dplyr-statements need to be quoted, so they can be found in the specified dataframe. The names of new variables as defined on the LHS of the summarise-expression are also quoted, while the function calls on the RHS will be evaluated.

14.2 Quotation

  1. Q: What happens if you try and use enexpr() with an expression? What happens if you try and use enexpr() with a missing argument?

    A: In the first case we’ll get an error:

    In the second case a missing argument is returned:

  2. Q: Compare and contrast the following two functions. Can you predict the ouput before running them?

    A: Both functions are able to capture multiple arguments and will return a named list of expressions. f1() will return the arguments defined within the body of f1(), because exprs() captures the expressions as specified by the developer during the definition of f1. f2() will return the arguments supplied to f2() as specified by the user when the function is called.

  3. Q: How are exprs(a) and exprs(a = ) different? Think about both the input and the output.

    A: In exprs(a) the input a is interpreted as a symbol for an unnamed argument. Consequently the output shows an unnamed list with the first element containing the symbol a. In exprs(a = ) the first argument is named a, but then no value is provided. This leads to the output of a named list with the first element named a, which contains the missing argument.

  4. Q: What does the following command return? What information is lost? Why?

    A: When we look at the captured expression, we see that the extra whitespaces and comments are lost. R ignores them when parsing an expression. They do do not need to be represented in the AST, because they do not affect the evaluation of the expression.

    However, it is possible to retrieve the original input through the attributes of the captured expression:

  5. Q: The documentation for substitute() says:

    Substitution takes place by examining each component of the parse tree as follows: If it is not a bound symbol in env, it is unchanged. If it is a promise object, i.e., a formal argument to a function or explicitly created using delayedAssign(), the expression slot of the promise replaces the symbol. If it is an ordinary variable, its value is substituted, unless env is .GlobalEnv in which case the symbol is left unchanged.

    Create four examples that illustrate each of the different cases.

14.3 Unquotation

  1. Q: Given the following components:

    Use quasiquotation to construct the following calls:

    A:

  2. Q: Explain why both !0 + !0 and !1 + !1 return FALSE while !0 + !1 returns TRUE.

    A: To answer this question we look at the AST of the first example:

    As the coercion rules are the same in all examples, we can use the precedence order (right to left) to explain all three examples:

    • !0 + !0:
      So the second zero gets coerced to FALSE and !FALSE becomes TRUE.
      0 + TRUE gets coerced to 1.
      !1 becomes !TRUE which is FALSE
    • !1 + !1:
      So !1 is FALSE.
      1 + FALSE is 1.
      !1 is !TRUE so FALSE.
    • !0 + !1:
      !1 is FALSE.
      0 + FALSE is 0.
      !0 is TRUE.
  3. Q: Base functions match.fun(), page(), and ls() all try to automatically determine whether you want standard or non-standard evaluation. Each uses a different approach. Figure out the essence of each approach by reading the source code, then compare and contrast the techniques.

  4. Q: The following two calls print the same, but are actually different:

    What’s the difference? Which one is more natural?

    A: call evalulates its ... arguments. So in the first call 1:10 will be evaluated to an integer (1, 2, 3, …, 10) and in the second call quote() compensates the effect of the evaluation, so that b’s second element will be the expression 1:10 (which is again a call):

    We can create an example, where we can see the consequences directly:

    I would prefer the second version, since it behaves more like lazy evaluation. It’s better to have call args depends on the calling environment rather than the enclosing environment,that’s more similar to normal function behavior.

14.4 Case studies

  1. Q: Implement arrange_desc(), a variant of dplyr::arrange() that sorts in descending order by default.

    A: We just have to catch the ... from arrange() as an expression and modify the expression to be wrapped inside desc(). Afterwards we evaluate this new code within a regular arrange() call:

    Let’s try it out

  2. Q: Implement filter_or(), a variant of dplyr::filter() that combines multiple arguments using | instead of &.

    A: This time we just need to collapse the ... arguments with |. Therefore we can use purrr::reduce() and afterwards we just need to evaluate the new code within a regular filter call:

  3. Q:Implement partition_rows() which, like partition_cols(), returns two data frames, one containing the selected rows, and the other containing the rows that weren’t selected.

    A: We just have to decide if we focus on integer subsetting via dplyr::slice() or logical subsetting via dplyr::filter(). The rest is straightforward. Since the implementations of both subsetting styles are completely equivalent we just choose one without any particular reason:

  4. Q:Add error handling to slice(). Give clear error messages if either along or index have invalid values (i.e. not numeric, not length 1, too small, or too big).

  5. Q:Re-implement the Box-Cox transform defined below using unquoting and new_function():

    A:

  6. Q:Re-implement the simple compose() defined below using quasiquotation and new_function():

    A: The implementation is straight forward. However, it can become tough to handle all bracktes correct at the first try:

14.5 Dot-dot-dot (...)

  1. Q: Carefully read the source code for interaction(), expand.grid(), and par(). Compare and constract the techniques they use for switching between dots and list behaviour.

  2. Q: Explain the problem with this defintion of set_attr()

    A: In this example we first learn that attributes must be named, as correctly given out by the error message. However, this behaviour mainly occures, because the first argument of set_attr() is named x as in the function call below. So the other argument in the set_attr() function call (1:10) is the only one, which is supplied as (unnamed) usage of the ellipsis. Therefore set_attr() tries to assign 1:10 as attribute to x = 10 and the error occures.

    The function becomes probably clearer and less error-prone when we name the first argument .x again. In this case 1:10 will get the (named) attribute x = 10 assigned: