Created
July 28, 2021 10:22
-
-
Save PabRod/5bbe91548db0b6478962c8d5c3f6425d to your computer and use it in GitHub Desktop.
Decorators in R
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
deco <- function(f) { | |
wrapper <- function(...) { | |
# <code prior to execution> | |
res <- f(...) | |
# <code after execution> | |
return(res) | |
} | |
return(wrapper) | |
} |
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
deco <- function(f) { | |
wrapper <- function(...) { | |
# Optional: extract arguments | |
args <- list(...) | |
# <more code prior to execution> | |
res <- f(unlist(args)) | |
# <code after execution> | |
return(res) | |
} | |
return(wrapper) | |
} |
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
log1starg <- function(f, filename = 'loginput.txt') { | |
wrapper <- function(x, ...) { | |
# Before execution | |
write(x, file = filename, append = TRUE) # Log the first argument only | |
res <- f(x, ...) | |
return(res) | |
} | |
return(wrapper) | |
} |
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
logger <- function(f, filename = 'log.txt') { | |
wrapper <- function(...) { | |
# Before execution | |
# Do nothing | |
res <- f(...) | |
# After execution | |
write(res, file = filename, append = TRUE) | |
return(res) | |
} | |
return(wrapper) | |
} |
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
timer <- function(f) { | |
wrapper <- function(...) { | |
# Before execution | |
op <- options(digits.secs = 6) # Our example is fast. Increase time resolution | |
print(paste("Ini time:", Sys.time())) # Show the clock before execution | |
res <- f(...) | |
# After execution | |
print(paste("End time:", Sys.time())) # Show the clock after execution | |
return(res) | |
} | |
return(wrapper) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment