Debugger and anonymous functions, purrr::map()

I'm wondering if there is a way to jump into anonymous functions when debugging them in, say, a purrr::map() call. Essentially, I get some errors when developing a function that, inside, uses some anonymous function arguments to map. I would like to do a call to debugonce() or similar to step into the anonymous function, inspect its values, and figure out what is wrong. I cannot figure out how to step into here -- I get into the guts of the purrr::map() implementation, not the anonymous function.

One solution is to pepper the anonymous code with browser() calls, and that works, but I am looking for something that can invoke the debugger without altering the code...
Advice appreciated.

library(dplyr)
library(purrr)

#;; I can run the interactive debugger if I name all of the functions
#;; Along the way
v <- 1:3
innerFunc <- function(i) {
    if (i == 2) stop()
    i
}

outerFunc <- function(vvec) {
    map(vvec, innerFunc)
}

#;; This allows me to step into the inner function at every invocation, and
#;; I can inspect the value of `i` before it stops.
debug(innerFunc)
outerFunc(v)



#;;;;;;;
#;; However, I don't know how to step into the inner function if I define it
#;; anonymously.  Is there a way?
outerFunc <- function(vvec) {
    map(vvec, ~{
        if (.x == 2) stop()
        .x
    })
}

#;; How do I step into the inner anonymous function via the debugger?
#;; This leads me down a rabbit-hole of map implementation guts.
debugonce(outerFunc)
outerFunc(v)

How about setting options(error = recover). After running your function, select the third option and it brings you into the inner function at the point of failure.

library(dplyr)
library(purrr)

options(error = recover)
v <- 1:3
outerFunc <- function(vvec) {
  map(vvec, ~{
    if (.x == 2) stop()
    .x
  })
}

outerFunc(v)

For my 2cents, anonymous functions are useful only when taking the time to think of a name for a function is more trouble than its worth, a simple function which is unlikely to fail and does something relatively trivial is one thing, but I think that from a programming best practice point of view, when you find that you need to debug a function that you had previously in-lined anonymously, this should potentially signal a warning to you, that the function might be worthwhile naming after all.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.