In the Environments chapter of the book
Advanced R, Hadley gives a function
where(name, env = parent.frame()) that finds the first environment where a given name is defined. The parameter env is the environment where the search begins. Its default value is the global environment (the environment where we normally work). The function was written recursively. I encourage you to study it first before reading on because I’m giving a solution here to one of the exercises, which asks to write a recursive function to find all environments that contain a binding for name.
Here’s my solution.
Let’s test it.
Now inside of where_all() I used a base R function exists() to check if name is in the current environment. But we don’t have to use it, instead, we can implement our own version using recursion. Below is how to do it.
We can simplify the code a bit by collapsing the if...else... inside the non-base case with the outside else clause. This makes the code a bit easier to read.
Let’s test it out.
Take a moment to compare exists2() and where_all(). Where does the recursive step happen? In exists2(), it happens when the fail case is triggered. But in where_all(), it happens after both the success and fail cases. So the take away is that although all recursions are the same in concept but they can differ in implementation. The key difference lies in where the recursive step happens.