# Am I being run backwards?

Your task is to write a program, function, or snippet that will output one value if run forward, and another if run backward. The program must run without errors.

The output can be any two distinct values, of the same data type. For example, 1 and 3, true and false, or 't' and 'f'. In languages without a concept of data types, such as brainf*** or text, any distinct values are allowed.

This is a code golf challenge, shortest answer per language wins. Note that snippets are allowed (so something like 1-2 is valid, but don't expect any upvotes).

• Related but IMO not a duplicate: codegolf.stackexchange.com/questions/16043/… Nov 9, 2019 at 3:29
• Is it just me, or does this seem like it would be an interesting candidate for code-bowling? Nov 10, 2019 at 6:50
• Does backwards mean character by character or line by line? Nov 11, 2019 at 17:16
• @CaptainMan Character by character Nov 11, 2019 at 20:07
• As much rep as someone wants if said person can think of a 1 byte answer. Feb 4, 2021 at 19:06

# Python 3, no comments or string literals, 106 bytes

x=quit
y=x.__class__
y.__pos__=x
x+x++x+x
x=__sop__.y
tnirp=__dda__.y
__ssalc__.x=y
tixe=x


I've never liked how comments and string literals let you "turn off" most of your language's syntax in challenges like this, so I wanted to see how far I could golf things without using either comments or string literals. This is what I came up with.

Since I don't have any way to disable the syntactical significance of parentheses, I cannot use the function call operator. Any attempt to do so would result in the reversed code having a closing parenthesis before the first opening parenthesis, which is invalid outside a comment or string literal. I also can't use def or container literals (aside from unparenthesized tuples), and my access to language features is in general extremely restricted.

One thing I can do is take advantage of Python's operator overloading to call functions implicitly. My ability to define any classes or functions is extremely limited, but fortunately, there are enough tools lying around in the built-in namespace for me to use. Most built-ins don't let me perform the attribute assignment I need to redefine their operator overloads, but (unless Python is run with one of the flags that disables site importing) the auto-imported site module adds quit and exit objects to the built-ins. These objects are instances of non-C classes, so I can reassign their operator overloads.

Setting __add__ to print lets me use addition to print things, and setting __pos__ to quit or exit lets me use the unary + operator to abort the program before the rest of the code runs. Without setting __pos__, I would need a bunch of additional code to make sure the "backwards" part of the code can find all the variables and attributes it needs to not fail. With __pos__, I only need to make sure the "backwards" code is still syntactically valid.

Forward, the code prints

Use quit() or Ctrl-D (i.e. EOF) to exit


Backward, the code prints

Use exit() or Ctrl-D (i.e. EOF) to exit


(The messages are slightly different on Windows.)

I also tried to figure out a way to do this by defining my own class instead of messing with quit.__class__. I got as far as the following:

if.1j:adbmal=1j
a=lambda:j1.fi
j1=a
a.__dict__=a.__globals__


class ton:adbmal is one of the very few combinations of class name and class body such that the class statement is syntactically valid backward. tressa, led, labolg, tropmi, and esiar would also have been valid class names (with a different class body, such as not fi), but ton is the only one where the reversed name can be part of an expression, giving the most flexibility.

if.1j:adbmal=1j assigns a value to adbmal to make the class body succeed, while still being syntactically valid backward.

The stuff with a and j1 lets me use j1.ton to refer to my ton class, which is still a valid expression backward.

At this point, I got stuck. I couldn't figure out how to get my class out of j1.ton and into a more useful variable. I can't assign attributes on j1.ton and still have valid syntax backward, so I can't set operator overloads. I also wanted to set builtins.__build_class__ to my class so I could abuse the class statement to construct instances without the function call operator, but trying to put j1.ton on the right side of an assignment produces invalid syntax backward.

If I had been able to name my class something like fi or tpecxe, I could have used tricks like b:j1.fi to get the class into an annotation and then a.__dict__=__annotations__ to get it into a.b, but I couldn't find any way to get the class statement and the annotation tricks to hook up. Anything that was compatible with the class statement was incompatible with the annotation tricks.

(You might wonder why I didn't abuse builtins.__build_class__ to call an existing function directly, like print. I couldn't figure out a way to do that and have the output be deterministic, and I wanted deterministic output.)

• +1, this is awesome. Nov 9, 2019 at 15:06

# JavaScript, 19 bytes

Returns true because of the assignment at the end, since JS treats that as defining a global variable. The first part is an arrow function, which is ignored. When run backwards, eurt is set to NaN (not a number), and since NaN is not greater than true (or equal), it returns false.

eurt=>true;NaN=true


Try it online!

eurt=NaN;eurt>=true


Try it online!

# JavaScript, 3 bytes

A snippet which outputs 1, or -1 in reverse. Very simple.

2-1


Try it online!

1-2


Try it online!

# JavaScript, 7 bytes

Abuses the not equal to operator and the not operator, will output false, or true in reverse. JavaScript uses NaN as not-a-number.

5==!NaN


Try it online!

NaN!==5


Try it online!

# JavaScript, 18 bytes

Another boring solution, with comments instead of subtraction. Returns 1, or 2 in reverse. I included the print statements in these.

print(1)//)2(tnirp


Try it online!

print(2)//)1(tnirp


Try it online!

# JavaScript, 7 bytes

Similar to the previous answer, but with assignment instead of equal-to. Uses the atob variable, which is a builtin in browser Javascript (decodes base64). Since TIO doesn't include browser builtins, I defined it just to keep it from erroring. Works as expected in console. Return true, or false in reverse.

2!=atob


Try it online!

bota=!2


Try it online!

• Why do you have to use NaN in the second snippet? That can be absolutely anything but 5, as far as I see. Nov 9, 2019 at 8:24
• @someone IDK, didn't think about it I guess. I kinda like the NaN being symmetrical trick, so I'll keep it Nov 9, 2019 at 15:07
• I was thinking of 0||1 Nov 10, 2019 at 23:02
• @Bergi That would work too, there're a huge number of 3-5 character solutions possible Nov 11, 2019 at 4:12
• @Bergi I just realized, that would be 1 every time... Nov 11, 2019 at 23:38

# J, 3 bytes

1"_


Try it online!

### one or infinity...

• 1"_ is the constant 1, turned into a verb of rank " infinity _. Hence always returns 1.
• _"1 is the constant infinity _, turned into a verb of rank $$$$. Hence always returns infinity.
• How does the ranking work? I've never seen anything like that in a programming language. Nov 9, 2019 at 15:16
• @RedwolfPrograms It's rank in the dimensional sense of linear algebra, rather than the colloquial sense of "a ranking." The basic idea is simple enough, but understanding it thoroughly is a serious undertaking. Nov 9, 2019 at 15:41

# Jelly, 2 bytes

+1


Try it online!

Prints 1.

# Jelly, 2 bytes

1+


Try it online!

Prints 2.

The reason for this is that Jelly's dyad-nilad structure chains differently on either side. +1 becomes a monad meaning "plus one", which is applied to the Left Argument, which defaults to zero. 1+ does not become a monadic chain here (if I remember correctly - correct me if my Jelly theory is off; I'm a bit rusty on the structural component), but rather is seen as 1 set as the Left Argument, and then + is applied as a dyad to (left, left) in the default case of no Right Argument, giving 1 + 1.

Great challenge; I almost feel like this is a cheese. I don't know if I should be happy with this solution or feel bad for having such a short and trivial solution >_<.

This uses Jelly's structure to be fancy. A more boring answer would just be 01 (prints 1) and 10 (prints 10), or any other two-digit number and its reverse (that isn't a palindrome).

• Cool solution! The higher level languages might be interesting to see, as well. +1 Nov 8, 2019 at 23:26

# bash, 12 bytes (no comments or string literals)

echo 0$ohce  Prints "0$ ohce"

echo $0 ohce  Prints "bash ohce" # bash, 11 bytes (no comments or string literals) echo ftnirp  Prints "ftnirp" printf ohce  Prints "ohce" # Wolfram Language (Mathematica), 10 bytes Print@ohcE  Try it online! Prints ohcE. Echo@tnirP  Try it online! Prints >> tnirP. # R, 2 bytes .1  Prints 0.1. 1.  Prints 1. Both numeric (double). tio Less trivial? and for an explicit true/false 2>1 # TRUE 1>2 # FALSE  tio • Shouldn't 1.<1 be 1.>1? – Adám Nov 10, 2019 at 7:57 • @Adám: Yes. Got my eyes crossed. Nov 10, 2019 at 9:43 • @AkselA That seems to happen a lot in this challenge...(-: Nov 10, 2019 at 15:15 • @RedwolfPrograms Is that a reversed sad smiley face? ;-) Nov 10, 2019 at 18:36 • @RobinRyder No, just a sideways one. I always forget which side the eyes are supposed to be on (;;;) Nov 11, 2019 at 1:53 # Keg, 2 bytes 10  Try it online! # Keg, 2 bytes 01  Try it online! When run forwards, it prints 10. When run backwards, it prints 01. I might try to create a non-trivial answer soon, as this seems like a really great challenge! • Also works in pretty much every language REPL. – Adám Nov 10, 2019 at 7:54 # Perl 5, 11 bytes say$-,yas


Try it online!

Outputs 0 when run forward. Outputs the current process number followed by 0 when run backwards.

# Actually, 2 bytes

Decrement empty value & push 1.

D1


Reversed program decrements 1, outputting 0.

1D


Try it online!

# 05AB1E, 2 bytes

The exact same answer ported to a different language.

<1


Try it online!

# POSIX sh (Dash, Bash, Zsh, ...), 3 bytes

: !


Try it online!

The builtin : discards its arguments and exits 0 (true). Reversed, ! negates the exit code of : and exits 1 (false).

• very cool. i was going to write a cross platform answer echo sey <=> yes ohce but this is way golfier! Dec 21, 2020 at 11:33

# HolyC, 12 bytes

Like the C version, except using the implicit print in HolyC

"0"; // ;"1"


Prints 0

"1"; // ;"0"


Prints 1

Spaces required by the compiler :)

# Poetic, 15 13 bytes

tis,A NAMETAG


Try it online!

Prints ASCII character 1 (SOH).

GATEMAN A,sit


Try it online!

Prints ASCII character 0 (NUL).

The previous answer ends with an "Unexpected EOF" error forwards because the END command (any ten-letter word) is omitted, and a "Mismatched IF/EIF" error backwards because EOF is encountered before an IF/EIF loop can end. The following answer terminates properly.

# Poetic, 51 bytes

the difference between I and certain ridiculous men


Try it online!

Prints a newline.

nem suolucidir niatrec dna I neewteb ecnereffid eht


Try it online!

Prints a newline and a "vertical tab" character.

(I really wanted to be able to make the programs make sense both backwards and forwards, but I'm not sure that's possible in English, and I don't know any other languages to try that out with.)

• The only thing I can think of that makes sense forward and backward (actually, neither) is tacocat racecar wow. Nov 11, 2019 at 16:28
• TIS A NAMETAG -> a person getting excited about a nametag. GATEMAN A SIT A command unto Gateman A; he must sit. Nov 11, 2019 at 16:40
• @ReinstateMonica Good one! Nov 11, 2019 at 16:40

# Haskell, 52 bytes

a=0--
--b tnirp=b#a
niam=main
1#a=niam
main=print a


==> prints "1"

a tnirp=niam
main=a#1
niam=main
a#b=print b--
--0=a


==> prints "0"

Explanation:

a=0--
-- FWD: define constant "a" to be 0 / BWD: No-op                                 --

--b tnirp=b#a
-- FWD: No-op / BWD: define a function "#" in two arguments and prints the       --
-- second                                                                        --

niam=main
-- FWD & BWD: define constant "niam" to be the same as "main"                    --

1#a=niam
-- FWD: define a function "#" in two arguments that produces "main" if the first --
-- argument is 1 / BWD: define constant "main" to be the result of the function  --
-- "#" applied to the arguments "a" and 1                                        --

main=print a
-- FWD: define constant "main" to be an IO action that prints the value of "a" / --
-- BWD: define a function "a" in one argument that always produces the value     --
-- of "niam"                                                                     --


Of course, there is also the shorter item:

# Haskell, 29 bytes

main=print 1--
--0 tnirp=niam


which is much less interesting.

# Dyalog APL

Boring solution using comments

0⍝1   => 0
1⍝0   => 1


Even more boring numeric solution:

10    => 10
01    => 1


Basic arithmetics:

2-1    => 1
1-2    => ¯1

• another: 0⊢1 and 1⊢0 Dec 21, 2020 at 8:18
• @Razetime yeah, it can be done using various operators - power, division, etc... but i found it pointless to include it here Dec 21, 2020 at 8:20
• embrace the boring Dec 21, 2020 at 8:23

# Whispers v3, 31 bytes

1 tuptuO >>
> 1
>> Output 1
0 >


Hooray for strict parsing rules!

The first and last lines are ignored, because they don't fit the right syntax. They come into action when reversed.

# Python 3, 17 bytes

print(1)#)2(tnirp


Try it online!

I promise this is the last trivial/cheese one I post; I'm trying to think of a more interesting solution. If I remember I'll see where I can get with this.

• At this point, Python devs should add tnirp as a function just to mess with y'all. Nov 9, 2019 at 17:12
• @DonThousand haha that would be funny :P Nov 9, 2019 at 17:13
• I keep reading tnirp as turnip Nov 11, 2019 at 16:59

# Pyth, 2 bytes

\"


Try it online!

Returns the string ' " ' (one set of double quotes)

# Pyth, 2 bytes

"\


Try it online!

Returns "\"

Oops, my earlier answer missed that they had to be the same data type. This answer returns two different strings, and relies on the fact that '\' makes a one character string of the input and that Pyth closes strings implicitly

• Oh, smart, using \" to escape a quote Nov 10, 2019 at 15:14

# Japt, 2 bytes

1g


Returns 1. Reverse returns -1.

g is the sign function when it has no arguments, and returns the sign of the argument minus the caller if called with an argument. So g1 would be the sign of zero minus one because the default input is 0

Test it

# 05AB1E, 2 bytes

Push 1 onto the stack & negates. (This results in -1)

1(


Negate empty value & push 1. Output 1 implicitly.

(1


Try it online!

• 3Í would also work. Try it online!
– mekb
Nov 9, 2019 at 4:03

# brainf*** 2 bytes

+.


Try it online!

Outputs 1 forwards, 0 backwards. Really randomdude999's answer

• Doesn't simply +. also work? It would output a 1 if run forwards and 0 if run backwards. Nov 9, 2019 at 6:33
• @randomdude999 Whoops, yeah it does. Man I'm bad at this so far Nov 9, 2019 at 6:37

## Ruby, 6 bytes

p:stup


Output

:stup


Reversed output

p


# Ceylon (Snippet), 20

The same trivial thing as in many other languages:

print(1);//;)2(tnirp


Outputs 1.

print(2);//;)1(tnirp


Outputs 2.

Given that parentheses need to be in the right order and you need print for output, I don't think this can be improved.

A full program or function needs even more braces/parentheses mirrored, so no chance of getting it better.

# Ceylon (anonymous function), 17

If we don't need to output anything, but just return it from an anonymous function, then this is enough:

()=>//
1.2
//>=)(


A function which returns 1.2 (a floating point value).

()=>//
2.1
//>=)(


A function which returns 2.1 (a floating point value).

# Ceylon (expression with return value), 3

If we accept just an expression (which then can be printed), then we don't even need any comments:

2.1


Gives 2.1 (a floating point value).

1.2


Gives 1.2 (a floating point value).

Try all of them online

# Wren, 32 bytes

Basically just a port of the Python answer.

System.write(1)//)0(etirw.metsyS


Try it online!

• I think you mean System.write(1)//)0(etirw.metsyS. Remember that orientation of brackets is preserved when the code is reversed Nov 9, 2019 at 8:16
• Thank you for noting that.
– user85052
Nov 9, 2019 at 12:59

# MathGolf, 2 bytes

This one does not have any nilads or dyads inside the program. Just monads.

±(


Try it online!

## Explanation

±  Find absolute value of the implicit 0
( Decrement 0, resulting -1.


Reversed:

(  Decrement 0, resulting -1.
± Find absolute value of -1, which results in 1.

• Interesting, using absolute value. +1 Nov 9, 2019 at 15:13

# Befunge-98 (PyFunge), 2 bytes

@,


Try it online!

Prints nothing by default, prints a null byte if reversed

# Turing Machine Code, no comments or string literals, 19 bytes

0 * 0 * 0
0 * 1 * 0


Reversed:

0 * 1 * 0
0 * 0 * 0


Try it online!

The code runs without errors, but does loop forever. Prints '0' forward, prints '1' reversed.

# MarioLANG, 3 bytes

:
+


Try it online!

Prints 0

+
:


Try it online!

Prints 1

# MarioLANG, 10 bytes

 ==
:+
==



Try it online!

Prints 0

 ==
+:
==


Try it online!

Prints 1

# Deadfish~, 2 bytes

oi


Try it online!

Boy, if that fruit hanged any lower, it'd be underground I tell you.

# TI-BASIC Non-trivial, 4 5 bytes

Disp "Disp :


This outputs 'Disp :'

Since TI-BASIC is token based, reversing it gives

:Disp "Disp


which outputs 'Disp'

Let me explain. 'Disp ' is one token which prints the given string to the home screen. First we are giving it a string of 'Disp :', so simple there. When reversed, since each 'Disp ' is one byte, we get the reversed code above. This reversed code starts with a ':', which ends the line, and means nothing here. The remaining code is 'Disp "Disp ', which runs and outputs 'Disp ' to the home screen.

# TI-BASIC Trivial, 2 bytes

If a program ends with a values, then it outputs it. This lets us do

12


which outputs 12, and reversed is

21
`

which outputs 21.

• I was waiting for a TI-Basic answer, +1 Nov 11, 2019 at 20:11