Tazinho / Advanced-R-Solutions

Set of solutions for the Advanced R programming book
https://advanced-r-solutions.rbind.io/
290 stars 118 forks source link

Answert to Exercise 10.5.1 is mistaken #220

Closed kayuwg closed 4 years ago

kayuwg commented 4 years ago
f <- mean
z <- 1
x <- list(f = mean, z = 1)
f <- function(x) x + 1
z <- 10

identical(with(x, f(z)), x$f(x$z))
#> [1] TRUE
identical(with(x, f(z)), f(x$z))
#> [1] FALSE
identical(with(x, f(z)), x$f(z))
#> [1] FALSE
identical(with(x, f(z)), f(z))
#> [1] FALSE

I believe (a) is the correct answer. I assign the copyright of this contribution to Malte Grosser and Henning Bumann.

henningsway commented 4 years ago

Hey @Elucidase,

thank you for your contribution. Could you elaborate, why you define f and z twice?

If you wrote the code like this all expressions would be true, right?

x <- list(f = function(x) x + 1, z = 1)
f <- function(x) x + 1
z <- 1

identical(with(x, f(z)), x$f(x$z))
identical(with(x, f(z)), f(x$z))
identical(with(x, f(z)), x$f(z))
identical(with(x, f(z)), f(z))
kayuwg commented 4 years ago

@henningsway By "equivalent", we should mean that they are identical under any condition. I think the exercise is asking when we use with are the non-function variables and/or functions found in the expression found from the list or from the global environment. The result is that both non-functions and functions are found in the list but not from the environment from which with is called. By redefining f and z in the global environment and make them different from the ones in the list, I tried to confirm the above claimed rule.

henningsway commented 4 years ago

I'm just not sure. I feel that the current in the book is correct though I may not see the issue fully. @Tazinho please reopen, if we need to change sth here.

Thank you @Elucidase for bringing this up anyway! (: