Skip to content

Instantly share code, notes, and snippets.

@peterhurford
Created June 10, 2015 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterhurford/c4681a1acff6cb29f3a6 to your computer and use it in GitHub Desktop.
Save peterhurford/c4681a1acff6cb29f3a6 to your computer and use it in GitHub Desktop.
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."
@robertzk
Copy link

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