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." |
This comment has been minimized.
This comment has been minimized.
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
This comment has been minimized.