Create a gist now

Instantly share code, notes, and snippets.

An R Function that Only Works When You Try to Debug it
# Debugging in R is much better than many languages, but sometime it can be
# frustrating. Here's a function that makes it even more frustrating --
# it only works when you try to debug it!
# The challenge:
### Write a function that, if the function has a browser in it, will execute
### every line correctly, but if it does not have a browser in it, it will
### error.
# The solution:
hate <- function() {
if (length(grep("browser()", body(hate))) == 1) {
stop("I hate you.")
}
"I returned fine."
}
# If you run it without a browser...
hate()
# Error in hate() : I hate you.
# ...But then add the browser.
hate <- function() {
browser()
if (length(grep("browser()", body(hate))) == 1) {
stop("I hate you.")
}
"I returned fine."
}
> hate()
# Called from: hate()
# Browse[1]>
# debug at #3: if (length(grep("browser()", body(hate))) == 1) {
# stop("I hate you.")
# }
# Browse[2]>
# debug at #6: [1] "I returned fine."
# Browse[2]>
# [1] "I returned fine."
@kirillseva

👍

@robertzk
body(hate) <- bquote({ getFunction("browser")(); .(body(hate)) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment