# I uppercase the source code, you reverse the input!

It's one of these again :D

Your task, if you wish to accept it, is to write a program/function (without any uppercase letters) that outputs/returns its string input/argument. The tricky part is that if I convert your source code to uppercase, the output must be reversed.

For simplicity, you can assume that the input is always a single line string containing only ASCII letters (a-z), digits (0-9), and spaces.

You do not need to handle empty input.

## Example

Let's say your source code is abc and its input is hello. If I write ABC instead and run it, the output must be olleh.

• How about switching case instead of just uppercasing it? So heLLO would become HEllo. Although this question would still be way too hard
– user
Sep 17 '20 at 16:52
• Anyone feel like using oOo CODE?
– user
Sep 17 '20 at 17:22
• Just a piece of advice: while it's always a good idea to post challenges in the Sandbox (no matter how simple they might seem), it's an extra good idea to do so if something similar has been done multiple times before (such as the "I <blank> the source code, you <blank> the input" challenges) Sep 17 '20 at 18:16
• Are the rules the same for letters in other languages like Φ/ϕ? Sep 17 '20 at 20:10
• The lowercase rule kicks pip outta this challenge :( Sep 18 '20 at 4:04

# 05AB1E, 1 byte

r


Try it online lowercase or uppercase!

Finally a question which I (a dumb brain) can answer! Thanks for this easy, yet fun challenge! (I do feel great, even though it requires little effort to make an answer in 05AB1E.)

### Wait, how?

r # reverses the stack. (Which literally does not do anything since only the
# implicit input is in the stack)
R # actually reverses the top string of the stack (Which is the implicit input).
# at the end, the input is automatically printed.

• That's awesome :) Sep 20 '20 at 3:07
• That's completely unfair! You didn't even put any effort on it and you get 40 upvotes, more than the sum of my answers. (Upvote)
– null
Sep 23 '20 at 5:20
• @null Sorry about that, but I do not have any idea how I got 40+ upvotes. (Honestly, I thought that I will get numerous downvotes) Sep 23 '20 at 6:49
• You beat me to it. I was thinking the same thing :) Sep 26 '20 at 18:09

# Python 3,  61 50 49  48 bytes

-1 thanks to benrg!

r=-1;ʳ=1;ᵖʳᵢⁿᵗ(ᵢⁿᵖᵘᵗ()[::r])


lower-cased / upper-cased

This works because

1. PEP-3131 was implemented in Python 3.0; and
2. These are the minimal length Unicode characters with no upper-case version which also normalise under the Normalization Form Compatibility Composition (NFKC) transformation to the basic latin characters one would normally use - TIO.

Note that identifiers, like r and the function names print and input, may be written like this but not keywords, like def or lambda.

(See the upper-casing of the code.)

• ...but it would make the code two bytes longer :) Sep 18 '20 at 8:42
• Time to enter some bugs for various IDEs... youtrack.jetbrains.com/issue/PY-44577 Sep 18 '20 at 8:47
• @JonathanAllan you're probably thinking of Print X Without X Sep 18 '20 at 9:18
• @ThomasWeller - nthistle's cop submission to Print X Without X employed the fact that we can use Unicode characters for identifiers. Sep 18 '20 at 9:30
• @whme No, the spec is that the lower-cased code gives the input back as-is. Sep 18 '20 at 12:22

# Python 3, 48 bytes

ᵖʳᵢⁿᵗ(ᵢⁿᵖᵘᵗ()[::b'b'[0]%3-1])


Lower: Try it online!

ᵖʳᵢⁿᵗ(ᵢⁿᵖᵘᵗ()[::B'B'[0]%3-1])


Upper: Try it online!

You can also verify that the upper program is truly uppercase.

It's unlikely we can write a program for Python 3 just using ASCII - we have no def, no lambda, and no builtin function calls. Also, all the properties of existing builtin objects are lowercase so we can't access those either. So instead our strategy is to look for Unicode characters that:

• Are not uppercase
• NFKC normalise to the character we want
• NFKC normalise to the character we want even after uppercasing

The following code does exactly that.

from unicodedata import normalize
for c in 'printinput':
for i in range(0x10ffff):
if not chr(i).isupper() and normalize('NFKC', chr(i)) == normalize('NFKC', chr(i).upper()) == c:
print(chr(i))
break
else:
raise Exception('no')

• Love the bytes trick! Sep 18 '20 at 8:43

# Jelly, 1 byte

ṛ


lower-cased / upper-cased

### How?

ṛ - Main Link: list of characters, S
ṛ - right argument (implicitly S)
- implicitly print

Ṛ - Main Link: list of characters, S
Ṛ - reverse
- implicitly print

• Ṛ is an uppercase letter with ṛ being its lowercase.
Sep 17 '20 at 17:36
• Totally fixed and now just 1 byte and future-proof. Sep 17 '20 at 18:13
• A bit late, but u/U also works: Try it online! Oct 10 '20 at 14:20
• @cairdcoinheringaahing I had that before, but since u is still free to be implemented as an atom this one is future-proof. Oct 10 '20 at 14:44

# APL (Dyalog Unicode), 10 bytes (SBCS)

Anonymous tacit prefix function.

⌽⍣('a'∊⎕a)


Try it online!

⌽⍣() apply reverse the following number of times:

'a'∊⎕a is "a" a member of the uppercase alphabet? (0)

### Uppercased

⌽⍣('A'∊⎕A)


Try it online!

⌽⍣() apply reverse the following number of times:

'A'∊⎕A is "a" a member of the uppercase Alphabet? (1)

In Dyalog APL, ⎕A is case-insensitive and always refers to the uppercase alphabet.

# Perl 5-p, 33, 25, 22 bytes

Thank's to @DomHastings who also had the same idea

m;$_=/.(?{$\=$&.$\})^/


uppercase

M;$_=/.(?{$\=$&.$\})^/


Try it online!

• This is a nice solution! Can't think of a different approach (this one didn't even jump out at me to be honest!) It's possible to potentially save a couple of bytes if you use s instead of next and add a ; to the end. It shouldn't be a problem because the input can only contain letters! Sep 18 '20 at 6:47
• Also, you can use \D as the search pattern to save a few more: Try it online! Sep 18 '20 at 6:51
• @DomHastings, indeed, i also though to m instead of next, but was looking if there could be a false match Sep 18 '20 at 8:00
• Also I didn't see your comments, when I modified [\0-\277] to ., i think we crossed Sep 18 '20 at 8:03
• Ahh, m is even better! Looks good! Sep 18 '20 at 8:14

# R, 122 bytes

\103=\162\145\166
\151\156\164\124\157\125\164\1468(c(\165\164\1468\124\157\111\156\164(\163\143\141\156(,""))))


try it online!

TRY IT ONLINE!

Includes only one letter, the lone c in the middle. The rest uses octal codes to get the equivalent of

C=rev
intToUtf8(c(utf8ToInt(scan(,""))))


With the lowercase c, the c makes no difference: we convert the input to integers, concatenate it with nothing, and convert back to characters. With an uppercase C, the integer vector in the middle gets reversed before being converted back.

# JavaScript (ES6), 46 bytes

Takes and returns an array of characters.

### In lowercase

s=>s.map?s:s["\162\145\166\145\162\163\145"]()


Try it online!

### In uppercase

S=>S.MAP?S:S["\162\145\166\145\162\163\145"]()


Try it online!

# JavaScript (ES6),  74  73 bytes

Saved 1 byte thanks to @Shaggy

Takes and returns a string.

### In lowercase

s=>s.big?s:[...s]["\162\145\166\145\162\163\145"]()["\152\157\151\156"]


Try it online!

### In uppercase

S=>S.BIG?S:[...S]["\162\145\166\145\162\163\145"]()["\152\157\151\156"]


Try it online!

• You could use the logic from your second solution, using s.big, in your first solution to save a byte. Sep 17 '20 at 18:43
• @Shaggy Good idea. Sep 17 '20 at 18:46
• The problem statement does explicitly say input is always a single line string, which I interpret to mean an actual string in JavaScript, rather than an array of characters. Sep 20 '20 at 3:05

_0(_1:_2)|'a'<'_'=_0 _2++[_1]
_0 _1=_1


Try it online! (lowercase)

_0(_1:_2)|'A'<'_'=_0 _2++[_1]
_0 _1=_1


Try it online! (uppercase)

Haskell requires that any variable name beginning with a capital letter is constructor of a declared type. This basically means we can't have any identifiers that start with a letter. (I think the options we actually have are LT, GT, and EQ but I wasn't able to find a use for any of these.) Luckily it is possible to write haskell programs without letters. We can start variable names with _ and we add numbers to the end to make it a valid name (certain symbols would work too).

To detect that which mode we are in we use the fact that strings change and do a comparison between a changing and static string, 'a'<'_' evaluates to False while 'A'<'_' is true.

# Ruby-p, 51 49 47 46 bytes

Saved a byte by using a shorter lexicographical comparison taken from @WheatWizard's Haskell answer.

?a<?_&&(f=->_{/.$/?($_=$;f[_+=$&]):$_=_})['']  Try it online! ?a<?_ tests whether the character a is lexicographically less than the character _. The test returns false, short-circuiting the && operator so that none of the remaining code is actually executed. The input is printed automatically thanks to the -p flag. ### Uppercase ?A<?_&&(F=->_{/.$/?($_=$;F[_+=$&]):$_=_})['']


Try it online!

Now we test whether A is lexicographically less than _. Here the comparison returns true so we proceed past &&. The code after && defines and calls a recursive lambda that reverses the input, which (because of -p) has been stored in the predefined global variable $_: (F=->_{ # define a lambda F with parameter _ /.$/?(     # if $_ contains at least one character, match the last one, then$_=$; # remove that character from$_
F[_+=$&] # recursively call F, appending that character to _ ):$_=_     # else set $_ to _, which now contains the full reversed input })[''] # call F, initialising _ to the empty string  Finally, $_ (now containing the reversed input) is printed automatically thanks to the -p flag.

• Very impressive. This might be the least clear Ruby code I've ever seen. Sep 20 '20 at 15:16
• @EricDuminil I took much inspiration from a master. Sep 20 '20 at 23:50

## Windows NT Batch + coreutils, 28 bytes

@if %os:~9%==t (tac)else cat


Explanation: %OS% contains Windows_NT and the substring starting at position 9 is compared with the letter t. If the batch file is uppercased then the comparison succeeds and tac is invoked otherwise cat is invoked.

• How will invoking cat or tac with no arguments print the arguments to the batch file backwards? Sep 17 '20 at 20:09
• @TessellatingHeckler The question allows you any string input, so I'm assuming the input will be on STDIN. Maybe I should have said that in my answer...
– Neil
Sep 17 '20 at 22:20

# J, 21 14 bytes

|.^:({.\:'a_')


Try it online!

## how

• |.^: Reverse the following number of times...
• :({.\:'a_') Grade down \: the string a_ and take the first element {..
• "Grade down" returns a list of indexes for the string, sorted descending. Thus \:'abc' would return 2 1 0, for example.
• "Grade down" will thus return 0 for the string a_, and 1 for the string A_, since _ is between a and A in the ascii alphabet.
• A is uppercase.
Sep 17 '20 at 18:10
• Thanks. Needed a new approach but fixed now. Sep 17 '20 at 18:32
• |.^:({.\:'a_')
Sep 17 '20 at 21:03
• Very clever. Thanks Adam. Sep 17 '20 at 21:05

# Wolfram Language (Mathematica), 24 bytes

#[[i=1;i^2;;-i^2;;i^2]]&


Try it online!

I is the built-in symbol for the imaginary unit $$\i\$$. Its value cannot be overridden without Unprotecting it first.

# APL (Dyalog Extended), 9 bytes

⌽⍣(<×'a')


Try it online (both lower and upper)!

In Extended, × (signum) on letters queries the letter case, giving -1 for lowercase and 1 for uppercase. Then < has implicit left arg of 0, so it tests if the right arg is positive (1) or not (0). Therefore, <×'a' evaluates to 0 and <×'A' evaluates to 1.

• Clever use of the Footer!
Sep 18 '20 at 4:46

# V (vim), 2 bytes

væ


Try it online!

And uppercased:

Væ


Try it online!

Hexdump:

00000000: 76e6                                     v


## How?

v enters 'visual mode' and begins selecting characters. At first, only 1 character will be selected. Then æ reverses every character that is selected. Reversing only 1 character does nothing.

But V will select every character on the current line, and then æ flips the whole line.

• Isnt Æ the uppercase of æ Sep 20 '20 at 1:30
• @Jasen Yes, it is. However, as the comments say That could get complicated. As long as the behavior is consistent for each character, it's fine to treat them (non-ASCII characters) either as lower/uppercase or as separate, non-letter characters. so I'm treating æ as a non-letter. Sep 20 '20 at 3:32

# Forth (gforth), 61 bytes

: f 'a 65 = if bounds 1- swap 1- -do i c@ emit 1 -loop then ;


A challenge where the case insensitivity of Forth has a use ... except that you don't have a string reversal built-in, so you have to loop through the string itself in reverse.

Almost all words in Forth are case-insensitive. The only case-sensitive part in the code is 'a or 'A, where the char's ASCII code (97 for a, 65 for A) is pushed to the stack. So we can compare it with a (trivially case-insensitive) numeric literal 65. If they're equal, the string is printed in reverse. Otherwise, the string is returned as-is.

• Now to find a place where space separation is useful. Nov 13 '20 at 8:15

# Brachylog, 3 bytes

ṡ↔|


and

Ṡ↔|


Try it online!

ṡ↔
ṡ   if input is a square matrix,
Ṡ   if input is a string,
↔   it is reversed
| otherwise return input unaltered


## PowerShell 7+, 56, 35 bytes

-join"$args"['a'[0]-97?99..0:0..99] # save as golf.ps1 and call .\golf.ps1 "string" # e.g. (running in anonymous function &{} for demo): PS C:\> &{-join"$args"['a'[0]-97?99..0:0..99]} '123 Alice'
123 Alice
PS C:\> &{-JOIN"$ARGS"['A'[0]-97?99..0:0..99]} '123 Alice' ecilA 321  With golfing suggestions from mazzy. Assuming the string is <= 100 characters. Change both the 99s to 1e5 notation for +2 bytes, much longer inputs, and much much slower code. ### old 56 byte version &{$a="$args";(gv a).name[0]-97?-join$a[$a.length..0]:$a}

e.g.

PS C:\> &{$a="$args";(gv a).name[0]-97?-join$a[$a.length..0]:$a} "123 Alice" 123 Alice PS C:\> &{$A="$ARGS";(GV A).NAME[0]-97?-join$A[$A.LENGTH..0]:$A} "123 Alice"
ecilA 321


The parameters to the anonymous function {} appear in the automatic variable $args and get stored in variable $a. String quotes "$args" cast to a single string. PowerShell is indifferent about the case of variable names, command names, property names, operator names, etc. so all the code runs in either case. gv is get-variable which looks for the a variable, finds its .Name (a or A depending on the case of the script - case is preserved), gets character [0] which is a or A again but this time as a [char] type, subtracts 97 (lowercase a value in ASCII), and ? : ternary operators whether that hit zero or non-zero, and either prints the original or reverse-indexes the characters and joins them into a reversed string. Printing is implicit. &{} runs the anonymous function. NB. TIO.Run only has PowerShell 5 or 6 at the time of writing, and ternary ?: is not in that version. • gv is nice. you can save some bytes wuth param($a) instead $a="$args";. You can omit &{} also because CodeGolf requires a Complete program. the complete Powershell program is a text in a ps1-script. Sep 18 '20 at 10:45
• gv is nice and too heavy. The [char]'a'-97 is sufficient :) Sep 18 '20 at 10:55
• @mazzy good ideas! Can push them a bit further and do away with param() and [char] and .Length. Sep 19 '20 at 11:26

# Pip, 6 bytes

[r_]@1


This is a function solution. Since it relies on the recently added unary R operator, it doesn't work on TIO, but a similar 7-byte version does:

[rv_]@2


### Explanation

Lowercase:

[  ]    Make a list containing
r       A random number between 0 and 1;
_      The identity function
@1  Get the item at index 1 (the identity function)


Uppercase:

[  ]    Make a list containing
R_      A function that reverses its argument
@1  Get the item at index 1, with cyclical indexing (the function)


The TIO version is the same idea, but uses the RV operator for reverse. It therefore has three items in the lowercase list (including v, which is -1) and gets the function using index 2 instead of 1.

# Raku, 28 bytes

{.?"{'flip'~^'    '}"()||$_}  Try it online! • $_ is the input to the function. Method calls lacking an explicit invocant are called on it.
• flip is the method to reverse a string.
• $obj."name"() is the syntax to call a method where the name is a string. The double quotes can contain interpolated values as usual. • $obj.?method means to call method on $obj if that method is defined for it, and otherwise return Nil. • ~^ is the stringy exclusive-or operator, which exclusive-ors the corresponding characters of its operands. Putting it all together, the uncapitalized program xors flip and a string containing four spaces, producing FLIP. That method is not defined for strings, so the .? method call returns Nil. Then Nil ||$_ evaluates to the original string. When the source code is uppercased, flip becomes FLIP, which when xor-ed with the spaces becomes flip, which when called on the input string, reverses it.

# SNOBOL4 (CSNOBOL4), 61 bytes

	&lcase 'a'	:f(r)
output =input
r	output =reverse(input)
end


Try it online!

SNOBOL by default case-folds identifiers and labels (unless &CASE is set to 0 or the flag -CASE 0 is used at the start of the program), so the only thing that really changes is the 'a' -> 'A', as SNOBOL uses case-sensitive pattern matching. Since 'A' is not lowercase, it jumps to the label R, which reverses.

# Klein 0X0, 68 bytes

Works in both 000 and 010

## Lower case

"a"1+-+?@      \
/!?:    (0)?/!?:<@?
>$:?!\?>:?!\$$/ \ (/ \ )/  Try it online! ## Upper case "A"1+-+?@ \ /!?: (0)?/!?:<@? >:?!\?>:?!\\( / \ (/ \ )/  Try it online! Most of this is just a program that reverses the input, which is not exactly easy in Klein. >:?!\?)0( :?!\?@ \ (//!?:<?/!?:<$$ / \( /  Try it online! To do the condition we have the very simple "a"1+-+?@  Which is an expression that is exactly zero, but becomes something else when a is capitalized. This is pretty much the exact method used by every other answer. The ?@ means that when it is zero it halts immediately (a cat program). Otherwise we continue execution to the reverse program bit. # JavaScript (V8), 4644 then by tch: 37 bytes $=([o,...a])=>o?o.sub?o+$(a):$(a)+o:a


Try it online!

Thanks to tsh for saving 7 bytes!.

Recursive function $ takes a string and destructures it into the first character o and an array a of the remaining characters. If lower case, o has a property sub it returns the forward string o+$(a). Otherwise, O has no property SUB and it returns the reverse string $(A)+O. The final iteration happens when $ is called with and empty array so there is no o. Here it returns a, an empty array [] which acts as and empty string "" in string addition.

# Charcoal -v, 24 bytes

ternaryless"a""_"reverse


Try it online! In upper case:

TERNARYLESS"A""_"REVERSE


Try it online! Explanation: If a or A as appropriate is less than _, the ternary then reverses the implicit input, otherwise just takes implicit input. The result is then implicitly printed.

# Japt, 1 byte

## Lowercase

ô


Try it

Partitions the input at falsey characters, but there's no such thing as a falsey character in JavaScript.

## Uppercase

Ô


Try it

The shortcut for w<space>, Japt's built-in for reversing.

# Coconut, 21 bytes

_->_[::('a'>'_')*2-1]


Try it online!

Try it uppercased!

# Keg, 9 bytes

?r\{9-=[^


Somehow, by making the answer valid, I saved bytes.

• I love how it looks like your Try it online! gets angry and demands me to TRY IT ONLINE!. Sep 18 '20 at 12:37
• @RedwolfPrograms try it online or die ;P Sep 19 '20 at 2:37

# MAWP, 19 bytes

%|11a{%%0~}<%0/>[;]


MAWP ignores lowercase letters, so this answer uses a conditional to check if subtraction has happened or not, and reverses based on it.

# oK, 13 bytes

.:9+23*7!"!g"


Try it online!

Explanation:

         "!g" /magic string
9+23*7!     /9 + 23 * (ascii value mod 7)
.:            /eval ascii values as a string


When the input is "!g" it becomes "||" which is evaluated as reversing twice.
When the input is "!G" it becomes "| " which is evaluated as reversing once.

## oK repl, 10 bytes

I'm going to say that this one doesn't count, because it relies on the fact that the oK repl works in mysterious ways.

.:4*54!"u"


Try it in repl!

When the input is "u" it becomes "\$" which evaluates as "string of expression". In the repl it is a noop when applied to strings.
When the input is "U" it becomes "|" which evaluates as reversing.

# Excel VBA, 58 bytes

Lowercase:

sub r(s)
if asc("a")=65then s=strreverse(s)
[a1]=s
end sub


Uppercase:

SUB R(S)
IF ASC("A")=65THEN S=STRREVERSE(S)
[A1]=S
END SUB


Output is to the cell A1 of the currently active sheet (if this is in a module) or the parent sheet (if this is in a sheet object). I'm a little concerned this doesn't comply with the spec, though, because VBA auto-formats much of the code once it's input:

Sub r(s)
If Asc("a") = 65 Then s = StrReverse(s)
[a1] = s
End Sub


Of course, the standard has been to not consider the extra formatting in the byte count so I presume we can also ignore the capitalization. Really, I'm more worried about the answer being too straightforward to be interesting rather than that technicality.