After poking around on the internet I wasn't able to find anyone who had written a quine in R (Edit: since writing this, have found several on SO, but am still interested in this one). So I figured I'd try my hand at coming up with one myself. My result was the (surprisingly short) code:
function(){}
which will output function(){}
when run. This takes advantage of the fact that a function name without parens or arguments after it will return the function's source code.
However, a program that "looks at itself" is not generally considered a true quine. There are two things I realized I don't understand in the course of trying to decide whether I'd written a "real" quine: (1) What constitutes a program "looking at itself" (from a quine standpoint) beyond use of file i/o and (2) the extent to which function(){}
(or similar commands like logical(0)
) are self referential when they print themselves. The former seems to be too subjective for SO, but I was hoping for some clarification on the latter. So...
When I run function(){}
, what exactly is happening that causes it to print its own "source code"? For example, is R loading an empty function into a local environment, evaluating that function, and then looking back at the code that defined it to print? Or, is it just looking at function(){}
and echoing its definition right away? Is there a fundamental difference between this and
f<-function(){cat("f<-");print(f);cat("f()")}
f()
in terms of how they both print themselves when run?
You don't completely get what's going on here. Actually, the code
function(){}
doesn't do anything apart from constructing a function without arguments and body, returning it and deleting it immediately after it's returned. Its output would be NULL
, so doesn't "recreate itself".
The output you see in the console, is not the output given by function(){}
but by print.function
. This is the S3 method that takes care of showing a function object in the console. What you actually do, is:
a <- function(){}
print(a)
rm(a)
A true R quine would be something like this:
m<-"m<-0;cat(sub(0,deparse(m),m))";cat(sub(0,deparse(m),m))
See also Wikipedia for this and other examples
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With