18
\$\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\$

39 Answers 39

60
\$\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.)


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\$
  • 4
    \$\begingroup\$ +1, this is awesome. \$\endgroup\$ – Redwolf Programs Nov 9 at 15:06
13
\$\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\$
  • 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\$ – someone Nov 9 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\$ – Redwolf Programs Nov 9 at 15:07
  • 1
    \$\begingroup\$ I was thinking of 0||1 \$\endgroup\$ – Bergi Nov 10 at 23:02
  • \$\begingroup\$ @Bergi That would work too, there're a huge number of 3-5 character solutions possible \$\endgroup\$ – Redwolf Programs Nov 11 at 4:12
  • \$\begingroup\$ @Bergi I just realized, that would be 1 every time... \$\endgroup\$ – Redwolf Programs Nov 11 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 `. Hence always returns infinity.
\$\endgroup\$
  • \$\begingroup\$ How does the ranking work? I've never seen anything like that in a programming language. \$\endgroup\$ – Redwolf Programs Nov 9 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 at 15:41
5
\$\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
    \$\begingroup\$ Cool solution! The higher level languages might be interesting to see, as well. +1 \$\endgroup\$ – Redwolf Programs Nov 8 at 23:26
5
\$\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\$

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

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\$

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\$
  • \$\begingroup\$ The only thing I can think of that makes sense forward and backward (actually, neither) is tacocat racecar wow. \$\endgroup\$ – Redwolf Programs Nov 11 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\$ – Reinstate Monica Nov 11 at 16:40
  • \$\begingroup\$ @ReinstateMonica Good one! \$\endgroup\$ – JosiahRyanW Nov 11 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.

New contributor
Andrew Ray is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\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\$
  • 5
    \$\begingroup\$ At this point, Python devs should add tnirp as a function just to mess with y'all. \$\endgroup\$ – Don Thousand Nov 9 at 17:12
  • \$\begingroup\$ @DonThousand haha that would be funny :P \$\endgroup\$ – HyperNeutrino Nov 9 at 17:13
  • 3
    \$\begingroup\$ I keep reading tnirp as turnip \$\endgroup\$ – legrojan Nov 11 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\$
  • \$\begingroup\$ Oh, smart, using \" to escape a quote \$\endgroup\$ – Redwolf Programs Nov 10 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\$
2
\$\begingroup\$

brainf*** 2 bytes

+.

Try it online!

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Doesn't simply +. also work? It would output a 1 if run forwards and 0 if run backwards. \$\endgroup\$ – randomdude999 Nov 9 at 6:33
  • \$\begingroup\$ @randomdude999 Whoops, yeah it does. Man I'm bad at this so far \$\endgroup\$ – HiddenBabel Nov 9 at 6:37
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\$
  • 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 at 8:16
  • \$\begingroup\$ Thank you for noting that. \$\endgroup\$ – A _ Nov 9 at 12:59
2
\$\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\$
  • \$\begingroup\$ Interesting, using absolute value. +1 \$\endgroup\$ – Redwolf Programs Nov 9 at 15:13
2
\$\begingroup\$

Befunge-98 (PyFunge), 2 bytes

@,

Try it online!

Prints nothing by default, prints a null byte if reversed

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

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.

\$\endgroup\$
2
\$\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\$
2
\$\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\$
2
\$\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\$
2
\$\begingroup\$

Deadfish~, 2 bytes

oi

Try it online!

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

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

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.

\$\endgroup\$
  • \$\begingroup\$ I was waiting for a TI-Basic answer, +1 \$\endgroup\$ – Redwolf Programs Nov 11 at 20:11
2
\$\begingroup\$

Bitwise Cyclic Tag, 2 bits (0.25 bytes)

With an input of 1 this should either set the data string to a null string or a string of length 2 in its next iteration.

01

Explanation:

0  Delete the leftmost data bit.
   Halt. No more instructions executed.
 1 Not executed

Reversed:

1  If the left-most data-bit is 1,
 0 Append a 0 to the data-string.
\$\endgroup\$
1
\$\begingroup\$

Japt, 2 bytes

c1

Return x rounded up to nearest multiple of N => output 0

Test it

1c

x default to 1 => output 1

Test it

\$\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.