29
\$\begingroup\$

Write a piece of code that takes a string as input, and outputs a piece of code in the same language that, when run, will output the initial input string.

It must be able to handle any combination of characters A-Z, a-z, and 0-9.

Example in Python:

import sys
print "print('" + sys.argv[1]  + "')"

Given the input of testing123, it will return print('testing123').

Since this is , the shortest answer in bytes will win.

\$\endgroup\$
  • \$\begingroup\$ Can it be a function? \$\endgroup\$ – totallyhuman Aug 13 '17 at 19:34
  • \$\begingroup\$ @manatwork (S)he edited it just now. \$\endgroup\$ – NoOneIsHere Aug 13 '17 at 19:42
  • \$\begingroup\$ Must input be a string? Or can it be an integer? \$\endgroup\$ – Shaggy Aug 13 '17 at 19:48
  • \$\begingroup\$ Must be able to handle both integer and string inputs. \$\endgroup\$ – Quartzic Aug 13 '17 at 20:00
  • 2
    \$\begingroup\$ Can we output a function as per the defauts on meta? \$\endgroup\$ – JAD Aug 14 '17 at 18:26

72 Answers 72

1
\$\begingroup\$

R (+ pryr), 27 25 bytes

pryr::f(function()cat(x))

which evaluates to the function:

function (x) 
function() cat(x)

which returns the function:

function()cat(x)

where x is defined in the scope of the first function, and taken directly from its input.

\$\endgroup\$
  • \$\begingroup\$ If I try this, I get: f=pryr::f(function()print(x)) f('test') function()print(x) <environment: 0x000000000aad19d8> I'm not sure I can actually then run that output code and get the string 'test'. Obviously this answer outputs a function that prints the string, I'm just not sure how literally to interpret the spec. \$\endgroup\$ – BLT Aug 14 '17 at 15:28
  • \$\begingroup\$ @BLT I am not sure what exactly your objection is. The returned function will print whatever was passed into x. \$\endgroup\$ – JAD Aug 14 '17 at 15:51
  • \$\begingroup\$ I guess it's more a question than an objection. The spec is "outputs a piece of code ... that, when run, will output the initial input string." Literally taken, that means I need to be able to run function()cat(x) and get the string, but that's not literally true - I'd have to save that function, and x would have to be saved somewhere ... does this mean that the spec isn't actually requiring "a piece of code that when run...`, and in fact is fine with returning a function that outputs the string? \$\endgroup\$ – BLT Aug 14 '17 at 17:23
  • \$\begingroup\$ I'm just getting hung up by the fact that if I run function()cat(x) then it won't actually return x - I have to actually invoke the function with x as input. Am I misunderstanding? Being overly literal? \$\endgroup\$ – BLT Aug 14 '17 at 17:26
  • \$\begingroup\$ @BLT I understand. I just assumed the standard definition of full program/function. I'll ask to clarify. \$\endgroup\$ – JAD Aug 14 '17 at 18:26
1
\$\begingroup\$

Haskell, 2 bytes

id

id returns it's argument unchanged.

id "abc" returns "abc" which evaluates to itself, which is a valid output method according to or standard rules. id is polymorphic and works for all kind of input types, so it also works for integer inputs.

The challenge requires to "output a piece of code". As @TannerSwett point out in a comment, the output of id is not valid Haskell source code, but a Haskell value or function that can be evaluated further, so it might also qualify as "code". If "code" means "source code" then we have a 4 byte answer

Haskell, 4 bytes (outputs source code)

show
\$\endgroup\$
  • \$\begingroup\$ Doesn't id "abc" really evaluate to the string abc (which would normally be written with quotation marks to indicate that it's a string), rather than to the string literal "abc"? I would think that "interpreting the output of id "abc" as a Haskell expression" would mean interpreting abc, not "abc", as an expression. \$\endgroup\$ – Tanner Swett Aug 14 '17 at 7:34
  • \$\begingroup\$ @TannerSwett: hmm, hard to tell. The challenge requires to "output a piece of code". If "code" means "source code", the you're probably right. If "code" means something that can be evaluated then I think id is a valid answer. I'll edit this in my answer. \$\endgroup\$ – nimi Aug 14 '17 at 17:05
1
\$\begingroup\$

Bash, 10 bytes

Saved 2 bytes thanks to @manatwork!

echo{,} $1

Try it online!

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 21 bytes

Maybe this is cheating...

LINPUT"?"+CHR$(34);S$

Asks for input with the prompt ?". (? is short for PRINT, and closing quotes are not required). So the "output" program is ?"<text>

\$\endgroup\$
1
\$\begingroup\$

Lua, 31 bytes

print('print([['..(...)..']])')

Try it online!

\$\endgroup\$
1
\$\begingroup\$

><>, 29 bytes

/->:?v";"o;
/l^  >"o''"o{ooo1

Takes input using the -s flag Prints a program that reads and print the original input character by character.

input -> 'i'o'n'o'p'o'u'o't'o;
\$\endgroup\$
1
\$\begingroup\$

R, 41 37 characters

function(x)"[[<-"(sys.call(),1,"cat")

How it works:

sys.call (makes only sense if used from within a function) returns the call; the first element of it is the name of the function; this is replaced on-the-fly by cat (which will print its arguments).

A nicer version:

sqk <- function(x)"[[<-"(sys.call(),1,as.name("cat"))
# will print cat(args) instead of "cat"(args) - both are functional but the 2nd is nicer

Example with output:

> sqk("The paws")
cat("The paws")
\$\endgroup\$
1
\$\begingroup\$

Java 8, 16 bytes

A rather strange challenge, especially given that the solution is only required to support alphanumeric strings.

s->"v->\""+s+'"'

This is a lambda from a string to the string representation of a lambda taking an empty argument of any type and returning the string.

\$\endgroup\$
  • \$\begingroup\$ Just to note - the solution doesn't have to only support alphanumeric strings, it's just that it's only required to support alphanumeric strings. \$\endgroup\$ – Quartzic Aug 14 '17 at 3:05
  • \$\begingroup\$ @Quartzic Right, that's what I meant. The wording in my post was ambiguous; I've corrected it. \$\endgroup\$ – Jakob Aug 14 '17 at 4:07
  • \$\begingroup\$ is it allowed to take an empty argument though? \$\endgroup\$ – ASCII-only Jun 23 '18 at 4:21
  • \$\begingroup\$ Yep, that's the consensus on the meta site. The interpretation we Java golfers have been using is that a single empty input may be added only if there are no other inputs and the empty input is unused. \$\endgroup\$ – Jakob Jun 23 '18 at 5:03
1
\$\begingroup\$

Julia 0.6, 8 bytes

s->()->s

Try it online!

Function that takes a string, and returns a closure that returns the string when called.

Alternately, a program outputting a program:

Julia 0.6, 28 26 bytes

print(:(show($(ARGS[1]))))

Try it online!

(Removed, of all things, a trailing whitespace. Smh. Also changed inner print to show.)

\$\endgroup\$
1
\$\begingroup\$

QBasic, 25 23 bytes

INPUT s$
?"?";
WRITE s$

Gets input from the user, and then prints a question mark followed by the input wrapped in double quotes. (Question mark is a shortcut for PRINT.)

\$\endgroup\$
0
\$\begingroup\$

Pyth, 3 bytes

+Nz

Try it online!

Explaination:

+Nz   expects any input
+     joins on same line
 N    quotation mark
  z   input as string
\$\endgroup\$
0
\$\begingroup\$

Lua, 30 bytes

print("print(\"".. ....."\")")

Try it online!

\$\endgroup\$
  • \$\begingroup\$ you can replace the " with ' to allow you to change the \"s to "s or you could change the \" to 's to get 28 bytes \$\endgroup\$ – Alex Allen Jun 20 '18 at 1:33
0
\$\begingroup\$

Mathematica, 15 bytes

"\""<>#<>"\"&"&

Not much.

\$\endgroup\$
0
\$\begingroup\$

Mathematica, 14 bytes

Defer@Print@#&

For input "test", this function will output Print["test"], which prints "test" when run.

\$\endgroup\$
0
\$\begingroup\$

Rexx (Regina), 14 bytes

say say arg(1)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

JavaScript ES6, 25 bytes (outputs code to "standard output")

s=>alert(`alert('${s}')`)

JavaScript ES6, 23 bytes (returns code, that outputs to "standard output")

s=>`alert('${s}')`

JavaScript ES6, 14 bytes (returns a function, that returns the result)

s=>`_=>"${s}"`
\$\endgroup\$
  • \$\begingroup\$ You're missing the quotation marks in your last solution, which should be your submitted solution as it's the shortest of the 3. \$\endgroup\$ – Shaggy Aug 13 '17 at 20:58
  • \$\begingroup\$ @Shaggy Right, let me add i \$\endgroup\$ – Bálint Aug 13 '17 at 20:59
  • 1
    \$\begingroup\$ You swapped string literals in your last function (and now it throws syntax error). Side note: it is not returning a function, it is returning a string which represents a function which returns the input. \$\endgroup\$ – user72349 Aug 13 '17 at 21:31
0
\$\begingroup\$

C++, 125 bytes

Warning : the code that will be printed will be invalid if input contains at least one of the character "

#include<iostream>
int main(int a,char**v){std::cout<<"#include<iostream>\nint main(){std::cout<<\""<<(a>1?v[1]:"")<<"\";}";}

C++, 116 bytes, undefined behavior if nothing is passed as console argument

If empty strings are considered as invalid input :

#include<iostream>
int main(int a,char**v){std::cout<<"#include<iostream>\nint main(){std::cout<<\""<<v[1]<<"\";}";}
\$\endgroup\$
  • \$\begingroup\$ Technically, for an empty string as input you'd have to do ./program "", so the second program is equally valid. \$\endgroup\$ – NieDzejkob Apr 8 '18 at 8:54
0
\$\begingroup\$

C#, 16 bytes

s=>$"()=>\"{s}\""
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 13 bytes

`,(read-line)

Try it online!

For instance, given the input john, the output will be "john", which evaluates to itself.

For a program that works through printing and not through the REPL:

Common Lisp, 20 bytes

`(princ,(read-line))

that produces (princ input-string).

\$\endgroup\$
0
\$\begingroup\$

><>, 37 bytes

i:1+?!v
-1"#"~<.1fo;!?l"<.09o;!?l"r}:

Try it online!

Fairly simple;

Takes input, prints out a printing loop with the string attached to the end.

\$\endgroup\$
0
\$\begingroup\$

Retina, 5 bytes

\`^
¶

Try it online!

For an input like testing123 returns the program:


testing123

which in turn produces the desired output.

Try it online!

There might be a trick to disable the newline append with shorter syntax, but I don't know it!

\$\endgroup\$
0
\$\begingroup\$

Swift, 47 bytes

print("print(\"\(CommandLine.arguments[1])\")")

I think this is pretty straight forward.

\$\endgroup\$
0
\$\begingroup\$

CJam, 2 bytes

q`

Explanation:

q  e# Input
`  e# String representation
\$\endgroup\$
0
\$\begingroup\$

Proton, 15 bytes

'print(%r)'&(%)

Try it online!

Binds 'print(%r)' to the left argument of % string formatting. When the input is given, it is applied as the second (right) argument which formats into the print statement.

\$\endgroup\$
0
\$\begingroup\$

Befunge-98 (PyFunge), 30 bytes

'":v
~\#[
<v">:#,_""#
<>4k,'@,

Try it online!

This prints a program in the form "...ihgfedcba">:#,_@, which prints abcdefghi...

Explanation

The code boils down to:

'":v    Push 2 quotation marks

~\#[    Get input and swap the top 2 items until EOF.
            Because every time we put a new value from input on the stack we also swap,
            the second quotation mark will float to the top, surrounding the input.

   >:#,_       A standard "print until the top is 0" loop
        ""#    Pushes a space, which is fine, since we control how much we print later
<v">:#,_"      When the IP gets reversed, we actually push the loop backwards onto
               the stack. This lets us print it later, instead of having to hardcode it.

 >4k,'@,       Prints 5 characters, being the printing loop from before, along with a @
<     @,       Prints an extra space, but it doesn't matter, and ends the program
\$\endgroup\$
0
\$\begingroup\$

J, 12 bytes

'echo',quote

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Ruby -n, 12 bytes

$><<"p'#$_'"

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Aceto, 14 13 11 bytes

'"drsJJp'pp

Try it online!

'"       push a quote character
  d       duplicate
   r       get input
    s       swap top stack items, so the input is between the two quotes
     JJ      Join top two items, 2x
       p  p    print
        'p      push literal:p 
\$\endgroup\$
0
\$\begingroup\$

Javascript, 20 bytes

Uses eval to make a new function from the input string.

a=>eval(`a=>'${a}'`)
\$\endgroup\$
0
\$\begingroup\$

Julia 0.6, 18 bytes

x->"print(\"$x\")"

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.