30
\$\begingroup\$

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

\$\endgroup\$
11
  • 3
    \$\begingroup\$ Is it just me, or does this seem like it would be an interesting candidate for code-bowling? \$\endgroup\$
    – Xcali
    Nov 10, 2019 at 6:50
  • 2
    \$\begingroup\$ Does backwards mean character by character or line by line? \$\endgroup\$ Nov 11, 2019 at 17:16
  • 1
    \$\begingroup\$ @CaptainMan Character by character \$\endgroup\$ Nov 11, 2019 at 20:07
  • 3
    \$\begingroup\$ As much rep as someone wants if said person can think of a 1 byte answer. \$\endgroup\$
    – Makonede
    Feb 4, 2021 at 19:06
  • 1
    \$\begingroup\$ Can the output be nondeterministic? (But they will always still be different) \$\endgroup\$
    – pxeger
    Jun 27, 2022 at 6:30

58 Answers 58

73
\$\begingroup\$

Python 3, no comments or string literals, 106 bytes

x=quit
y=x.__class__
y.__add__=print
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. For platform-independent output at the expense of 3 extra bytes, you can replace the middle line with x+1++x++2+x, printing 1 when run forwards and 2 when run backwards.)


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
class ton:adbmal
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.)

\$\endgroup\$
1
  • 4
    \$\begingroup\$ +1, this is awesome. \$\endgroup\$ Nov 9, 2019 at 15:06
15
\$\begingroup\$

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!

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

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 1. Hence always returns infinity.
\$\endgroup\$
2
  • \$\begingroup\$ How does the ranking work? I've never seen anything like that in a programming language. \$\endgroup\$ Nov 9, 2019 at 15:16
  • \$\begingroup\$ @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. \$\endgroup\$
    – Jonah
    Nov 9, 2019 at 15:41
6
\$\begingroup\$

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

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

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"

\$\endgroup\$
4
\$\begingroup\$

brainf*** 2 bytes

+.

Try it online!

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

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

Wolfram Language (Mathematica), 10 bytes

Print@ohcE

Try it online!

Prints ohcE.

Echo@tnirP

Try it online!

Prints >> tnirP.

\$\endgroup\$
4
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\begingroup\$ Shouldn't 1.<1 be 1.>1? \$\endgroup\$
    – Adám
    Nov 10, 2019 at 7:57
  • \$\begingroup\$ @Adám: Yes. Got my eyes crossed. \$\endgroup\$
    – AkselA
    Nov 10, 2019 at 9:43
  • \$\begingroup\$ @AkselA That seems to happen a lot in this challenge...(-: \$\endgroup\$ Nov 10, 2019 at 15:15
  • \$\begingroup\$ @RedwolfPrograms Is that a reversed sad smiley face? ;-) \$\endgroup\$ Nov 10, 2019 at 18:36
  • \$\begingroup\$ @RobinRyder No, just a sideways one. I always forget which side the eyes are supposed to be on (;;;) \$\endgroup\$ Nov 11, 2019 at 1:53
4
\$\begingroup\$

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

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

7, 2 characters, 1 byte in 7's encoding

31

Try it online! (forwards)

Try it online! (reversed)

This should be the first valid 1-byte solution (because the existing 1-byte solution in BCT requires a particular value on its input to work, and isn't counting it in the byte count – that could only be assumed in a full program, and BCT full programs can't do I/O and must wipe all their working memory to be able to halt, thus have no way to halt with a value). 7's encoding packs multiple characters into a single byte: here are xxd hexdumps for the forward and reverse programs:

00000000: 67                                       g
00000000: 2f                                       /

This conceptually outputs a string: 31 for the forwards program, and an empty string for the backwards program. The output encoding is set to be the same as the input encoding; so if you encode the program in 7's encoding, you'll get a single byte of output which encodes the string 31 (and if you use ASCII instead, you'll get two bytes that encode the string 31 in ASCII).

Explanation

On the first pass through the program, the 3 appends a "print and pop" command to the stack, and the 1 appends a "push empty stack element" command to the stack. So, we end up forming a program on top of the stack. At the end of the first pass through the program, 7 will run the resulting program, but without popping it from the stack.

With the forward version of the program, the "print and pop" command will attempt to print the program consisting of a "print" command and a "pop" command. That isn't a valid literal, so the 7 interpreter will construct code that's capable of constructing that stack element and print that instead; in this case, the code it finds for for "push a stack element that generates a 'print and pop' command then a 'push empty stack element command'" is 731 (i.e. basically the program we wrote, although our program appends to an implicit empty stack element, whereas the reconstructed program makes a new one). The print routine interprets the 7 as a command to set the output encoding to the same encoding that was used for the source code, and then the 31 is interpreted as a literal and gets printed. The command in question pops two things in total (the thing it's printing and the element below), so the stack now contains no data and thus there are no more passes through the program; it just exits (even though we push an empty stack element after this point, those don't affect the end-of-program behaviour).

With the reverse program, we're pushing the empty stack element before the print attempt, rather than the other way round, so it's now an empty string that gets printed, and the remnants of the program (which are below it) get popped without printing them. Everything is now the same as in the forward program, so the reverse program also exits naturally and without error.

\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
1
  • 6
    \$\begingroup\$ Also works in pretty much every language REPL. \$\endgroup\$
    – Adám
    Nov 10, 2019 at 7:54
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.
\$\endgroup\$
1
  • \$\begingroup\$ Interesting, using absolute value. +1 \$\endgroup\$ Nov 9, 2019 at 15:13
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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

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

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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ another: 0⊢1 and 1⊢0 \$\endgroup\$
    – Razetime
    Dec 21, 2020 at 8:18
  • \$\begingroup\$ @Razetime yeah, it can be done using various operators - power, division, etc... but i found it pointless to include it here \$\endgroup\$ Dec 21, 2020 at 8:20
  • \$\begingroup\$ embrace the boring \$\endgroup\$
    – Razetime
    Dec 21, 2020 at 8:23
3
\$\begingroup\$

Whispers v3, 31 bytes

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

Try it online!, !enilnO tI yrT

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.

\$\endgroup\$
3
\$\begingroup\$

Fig 0.1.0, \$2\log_{256}(96)\approx\$ 1.646 bytes

,"

See the README to see how to run this

Argh. Beaten by Halfwit by more than half a byte. In the forward position, it prints a single newline. Backwards, ",, it prints a comma followed by a newline.

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

Make, 14 15 bytes

x:#
	#$@$#	
#:y

Try it online!

Updated to add a trailing tab on the second line...

Here's another one that's not as short, but seems interesting enough to post...

Forwards it prints x and backwards it prints y. It works by referencing the $@ symbol, which is defined as the target being made. The "command" run is just a comment to the shell, so it's a no-op. But by default Make echos the commands it runs.

Also, the $# reference doesn't cause an error, and evaluates to an empty string, which allows #$@$# to work both directions without having to add more characters.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice answer, but I think it should be 15 bytes, because the second line should end with tab. Also I think it would be nice to tell that $# is variable with empty value as it confused me a bit at first, because I am not that much familiar with Make. \$\endgroup\$
    – Jiří
    Jun 27, 2022 at 19:45
  • 1
    \$\begingroup\$ Good point... there is missing trailing tab on the second line. I'll update the answer. And I'll add a note about "$#" evaluating to an empty string. \$\endgroup\$
    – cnamejj
    Jun 28, 2022 at 4:31
3
\$\begingroup\$

Vyxal, 4 bits1, 0.5 bytes

2

Try it Online! (link is to bitstring) The bitstring form of this is 0101, which translates to 2.

Reversed - Try it Online! (outputs 0)

If we stretch the rules a bit, we can get two bits: Try it Online! !enilnO ti yrT, which respectively output an empty string and 0 - 0 and 1 in unary.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
3
  • 7
    \$\begingroup\$ At this point, Python devs should add tnirp as a function just to mess with y'all. \$\endgroup\$ Nov 9, 2019 at 17:12
  • \$\begingroup\$ @DonThousand haha that would be funny :P \$\endgroup\$
    – hyper-neutrino
    Nov 9, 2019 at 17:13
  • 4
    \$\begingroup\$ I keep reading tnirp as turnip \$\endgroup\$
    – legrojan
    Nov 11, 2019 at 16:59
2
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Oh, smart, using \" to escape a quote \$\endgroup\$ Nov 10, 2019 at 15:14
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ would also work. Try it online! \$\endgroup\$
    – mekb
    Nov 9, 2019 at 4:03
2
\$\begingroup\$

Ruby, 6 bytes

p:stup

Output

:stup

Reversed output

p
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

Wren, 32 bytes

Basically just a port of the Python answer.

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

Try it online!

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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