Created
June 10, 2015 19:39
-
-
Save peterhurford/c4681a1acff6cb29f3a6 to your computer and use it in GitHub Desktop.
An R Function that Only Works When You Try to Debug it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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." |
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
👍