I read some post where Hadley made a joke about a self destructing function. I thought this would be relatively simple to implement but turns out it's not.
Here is an attempt to write a function named self_delete
that is a quine and attempts to self destruct after printing its body. The idea was to search for the function's name in .GlobalEnv
and delete it but that doesn't work. I would like to understand why this is the case.
self_delete<- function(){
print(body(self_delete))
rm(list=lsf.str(pattern="self_delete"))
}
Calling the above prints the following as expected but does not delete itself from .Globalenv
, what am I missing? I did try with rm
and ls
too with no luck
self_delete()
{
print(body(self_delete))
rm(list = lsf.str(pattern = "self_delete"))
}
You forgot to set the envir
argument to rm()
, so it's trying to delete self_delete
from the calling frame, not from globalenv()
.
This works:
self_delete <- function(){
print(body(self_delete))
rm("self_delete", envir = globalenv())
}