Site icon R-bloggers

Quine with R

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Quine is a self-reproducing function or a computer program that will output its source source or itself. Terms used are for these programs are also self-replicating programs, self-reproducing programs or self-copying programs (courtesy of wikipedia).

Many programming languages have been known to do this, for example in Python, a simple Quine would look like this:

a= 'a=%b;print(a%%a)';print(a%a)

Similar to Python, quine can be written in R as well. Simple example would be:

a<-"a<-0;cat(sub(0,deparse(a),a))";cat(sub(0,deparse(a),a))

Example consists of two blocks; the first block contains the function that will perform the process of replication

"a<-0;cat(sub(0,deparse(a),a))"

And the second part contains the code that will be outputted.

cat(sub(0,deparse(a),a))

When we run the command, the script will return itself, revealing the complete input command.

Word quine primarily comes from the biology, precisely from the self-replication, and it consists of two parts, first part is the code that performs the replication and the second is the data that contains all the code, script, instructions to perform the replication process.

The value of variable a can hold basically any text or any additional information, since the function in R is using string manipulation functions sub and deparse.

Deparse is used to preserve the quotations in original input command and sub is used to get the the first and the second block of code.

Happy R-coding!!!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.