# Script that outputs a script that prints a given input

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.

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

# 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.

• 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. – BLT Aug 14 '17 at 15:28
• @BLT I am not sure what exactly your objection is. The returned function will print whatever was passed into x. – JAD Aug 14 '17 at 15:51
• 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? – BLT Aug 14 '17 at 17:23
• 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? – BLT Aug 14 '17 at 17:26
• @BLT I understand. I just assumed the standard definition of full program/function. I'll ask to clarify. – JAD Aug 14 '17 at 18:26

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

• 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. – Tanner Swett Aug 14 '17 at 7:34
• @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. – nimi Aug 14 '17 at 17:05

# Bash, 10 bytes

Saved 2 bytes thanks to @manatwork!

echo{,} $1  Try it online! # Lua, 31 bytes print('print([['..(...)..']])')  Try it online! # AWK, 25 bytes $0="BEGIN{print\""$0"\"}"  Try it online! Should work for most input other than ". If some (possibly empty) input is allowed for the secondary program this could be shortened to: $0="$0=\""$0"\""


# dc, 10 bytes

91Pn93PACP


Try it online!

Straightforward: print an open bracket, then the input, then the close bracket and the letter p for the print command. 91Pn23920P also works.

# ><>, 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;


# 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")


# 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.

• 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. – Nathan Goller-Deitsch Aug 14 '17 at 3:05
• @Quartzic Right, that's what I meant. The wording in my post was ambiguous; I've corrected it. – Jakob Aug 14 '17 at 4:07
• is it allowed to take an empty argument though? – ASCII-only Jun 23 '18 at 4:21
• 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. – Jakob Jun 23 '18 at 5:03

# 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:

print(:(show($(ARGS[1]))))  Try it online! (Removed, of all things, a trailing whitespace. Smh. Also changed inner print to show.) # 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.) # APL (Dyalog Unicode), 12 bytes ∊'⍞←'''⍞''''  Outputs programs as ⍞←'input' Try it online! # 05AB1E, 0 bytes Try it online! Takes input surrounded in any of "‘’“” (as long as the first and last quotes are the same). # Explanation The program immediately reaches the end, so it triggers implicit output. Since the length of the stack (0) is less than the arity of the print function (1), it implicitly checks if there's input (which there is), and if so uses it as the argument. It outputs with a trailing newline, but that doesn't matter since newlines are nops in 05AB1E. ### TL;DR: The null program in 05AB1E is a one-line cat. Finally, each of "‘’“” are used for strings. The difference is that ‘’“” are used for compressed strings while " is regular. However, ‘’“” treat all ASCII characters normally, so they don't make a difference for this challenge. Declaring strings pushes them to the stack, so now the original input is on the stack of the generated program. At the end, it implicitly outputs the top of the stack - which is, you guessed it, the original input. # Example Say you input "testing123". Since the program is a one-line cat, it outputs "testing123". Running this will push everything between "" to the stack, therefore pushing the string "testing123". Finally, it implicitly outputs the top of the stack, printing testing123. # naz, 110 bytes 2x0v1x1f1r3x0v4e2x1v2f0x1x2f1v3x0v3e1s2x1v0m1a1o8m4m3m1a1o2f0x1x3f0m1a1o8m3m5m9s1o2d7s1o3d7m3s1o1f0x1x4f0a0x1f  Works for any null-terminated input string, with some caveats: programs generated for strings containing any control characters between SOH and TAB (values 1-9) will produce incorrect output due to a language quirk, and programs generated for strings containing any control characters between VT and US (values 11-31), or the control character DEL (value 127), will error out with invalid output value if run. Luckily, none of these cases are required by the challenge. Output programs are generated naïvely and are thus near-irreducible; the output program for an input of ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 will take around 125 milliseconds to generate, but around 10 seconds to run. Explanation (with 0x commands removed) 2x0v # Set variable 0 equal to 0 1x1f # Function 1 1r # Read a byte of input 3x0v4e # Goto function 4 if it equals variable 0 2x1v # Otherwise, store it in variable 1, 2f # and call function 2 1x2f # Function 2 1v # Set the register equal to the value of variable 1 3x0v3e # Goto function 3 if this equals variable 0 1s2x1v # Otherwise, subtract 1 from variable 1, 0m1a1o8m4m3m1a1o # output "1a", 2f # and jump back to the start of function 2 1x3f # Function 3 0m1a1o8m3m5m9s1o2d7s1o3d7m3s1o # Output "1o0m" 1f # Call function 1 1x4f # Function 4 0a # Add 0 to the register 1f # Call function 1  # Pyth, 3 bytes +Nz  Try it online! Explaination: +Nz expects any input + joins on same line N quotation mark z input as string  # Lua, 30 bytes print("print(\"".. ....."\")")  Try it online! • 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 – Alex Allen Jun 20 '18 at 1:33 # Mathematica, 15 bytes "\""<>#<>"\"&"&  Not much. # Mathematica, 14 bytes Defer@Print@#&  For input "test", this function will output Print["test"], which prints "test" when run. # Rexx (Regina), 14 bytes say say arg(1)  Try it online! # JavaScript ES6, 25 bytes (outputs code to "standard output") s=>alert(alert('${s}'))


s=>alert('${s}')  # JavaScript ES6, 14 bytes (returns a function, that returns the result) s=>_=>"${s}"

• You're missing the quotation marks in your last solution, which should be your submitted solution as it's the shortest of the 3. – Shaggy Aug 13 '17 at 20:58
• @Shaggy Right, let me add i – Bálint Aug 13 '17 at 20:59
• 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. – user72349 Aug 13 '17 at 21:31

## 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]<<"\";}";}

• Technically, for an empty string as input you'd have to do ./program "", so the second program is equally valid. – NieDzejkob Apr 8 '18 at 8:54

# C#, 16 bytes

s=>\$"()=>\"{s}\""


# 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).

# ><>, 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.

# 05AB1E, 3 bytes

'"«


Try it online!

Surround input with quotes.

• This doesn't work, putting a quote mark after text doesn't interpret that text as a string... maybe you were looking for ì (prepend), since you want a quote at the start of the text, not the end. Also, per meta consensus you're allowed to take input surrounded in quotes, making a 0 byter possible. ;) – Makonede Dec 21 '20 at 2:24

## 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!

# Swift, 47 bytes

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


I think this is pretty straight forward.

# CJam, 2 bytes

q


Explanation:

q  e# Input
e# String representation

• 1 byte by removing the  and taking input surrounded in quotes. – Makonede Jan 11 at 19:19

# 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.

# 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
`