A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

  • Gets a number (either 0 or 1) from STDIN.

  • If that number is 0, print out 0 and terminate.

  • If that number is 1, print out 1 forever.


Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

  • take input from STDIN or an acceptable alternative
    • If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program
  • must output to STDOUT or an acceptable alternative
    • If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.
  • when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory
  • the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

  • if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).


The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

  • \$\begingroup\$ Can we assume that the program halts when the processor finishes executing the written code, for a machine code entry? \$\endgroup\$ – lirtosiast Nov 3 '15 at 16:58
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ – Cruncher Nov 3 '15 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ – a spaghetto Nov 3 '15 at 17:38
  • 4
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ – Addison Crump Nov 6 '15 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ – Mooing Duck Nov 10 '15 at 1:13

388 Answers 388

1 5 6 7 8 9 13

SWI-Prolog, 45 bytes


The put and get predicates work with character codes, so we need to test against 48 for the 0 case. If that succeeds, halt; if it fails, try m(X) recursively instead.

To run from Linux command-line, put the code in a file and execute swipl -qs truth.pro. (The q is optional; it suppresses extra output from the interpreter.) Or, try it here.

  • \$\begingroup\$ I guess you can remove the halt, since directives are only executed once (next() and close()). But the link somehow doesn't work, it gives an error. \$\endgroup\$ – Mostowski Collapse Nov 7 '15 at 10:25
  • \$\begingroup\$ On the other hand to be ISO Prolog compliant, you would need initialization/1 swi-prolog.org/pldoc/man?predicate=initialization/1, since arbitrary directives are not allowed. The above would run in GNU Prolog. \$\endgroup\$ – Mostowski Collapse Nov 7 '15 at 10:30
  • \$\begingroup\$ @j4nbur53 The reason why I included halt is that with swipl on Ubuntu, not including it drops to a user prompt after the above code executes. I don't know what the exact policy on that is, but it seems like extraneous output that can be avoided, so I figured I'd better avoid it. \$\endgroup\$ – DLosc Nov 7 '15 at 23:04

Batch, 31 bytes

@IF 0%1==01 echo 1&%0 1
@echo 0

On my machine, running <script name> 1 twice from the command prompt caused CMD to crash. The first time it stopped after printing a lot of lines with 1s on it. (Presumably because of CMD running out of memory.)


@ – This tells CMD not to print the commands on this line. (Output will still be printed.)
%1 – This will be substituted with the first argument given.
%0 – This will be substituted with the script name.

The first line will output 1s and then launch the script itself with an argument 1 if the script was called with the argument 1. Otherwise, the condition evaluates to false and the script will proceed to the second line. It will then output 0 and exit.


Math++, 11 bytes



1:Set a to a number from the input
2:Print a (the designator ">out" is implied if none is specified)
3:If a is 1, go to 2; if a is 0, exit
  • \$\begingroup\$ Could you add an explanation? \$\endgroup\$ – Addison Crump Nov 4 '15 at 12:45
  • \$\begingroup\$ @VoteToClose Done \$\endgroup\$ – SuperJedi224 Nov 4 '15 at 13:49

Loader, 30 bytes

run from m.ldr (or replace the m in the last line with the name of the file)

~B:set B =@IN
print B
B:load m

Theoretically infinite, in practice will result in Error: Stack Overflow in the reference implementation.

With comments:

~B:set B =@IN !!If B is zero (the default for uninitialized variables), set B to a number from the input
print B !!Exactly what it says on the tin
B:load m !!If B is nonzero, load a separate instance of this module on a copy of the current memory space

TML, 14 bytes

d={1 or 0}/0000-1111/





Finally I was able to use my language for something :) Since TML hasn't got an IO support (yet), the value must be hardcoded in the tape, but it should work as intended! If the value is 0 it halts (goes to card 0), else it will print an infinite string of 1s

Otherwise I have a 2 cards solution using the default tape:

{0 or 1}/0000-1112/0112-1112/

Burlesque, 6 bytes



ri -- read int
qJ -- shortcut for {J}, which is a shortcut for {^^}
      ^^ = duplicate
w! -- while loop

Mind you that the reference implementation of the interpreter buffers output so you'll run out of memory sooner or later before seeing any output in case you provide "1" on STDIN.


GolfScript, 9


Equivalent to q~{_p}h; in CJam.


HSPAL, 60 bytes


><>, 15 bytes

i6%   \

i        Input character (by code point)
 6%      Modulo the top item on the stack by 6
      \  go to second layer

::       Duplicate the top item on the stack twice
  n      Print the top item of the stack as an integer
   ?!    If the top item on the stack is 0:
     ;    End program.
      >  Otherwise, move forward.

Microscript II, 3 bytes


Essentially a translation of the Microscript answer


PHP, 33 37 39 29 bytes

Pretty straight forward:


Runs from command line:

php truth.php 1


  • Added 10 bytes as the program must take input from STDIN if possible. Thanks to Martin Büttner for pointing it out. :)
  • Saved 2 bytes by using if and for instead of while. Thanks to BLackhole
  • Saved 2 bytes by placing everything into the for-loop. Thanks to fschmengler.
  • Saved 2 bytes by rewriting the 2nd expression of the for-loop.
  • \$\begingroup\$ Actually it's 39 because you have to add either <? or the -r flag \$\endgroup\$ – Fabian Schmengler Nov 5 '15 at 16:11
  • \$\begingroup\$ But you can save one byte more with this: <?for($f=fgetc(STDIN);(print$f)&$f;); - print is like echo but has a return value (always 1) \$\endgroup\$ – Fabian Schmengler Nov 5 '15 at 16:17
  • \$\begingroup\$ @fschmengler Thanks for your feedback. I made it even 2 bytes shorter, by switching (print$f)&$f to $f&print$f. There is a general discussion about the byte count here: Is the PHP opening tag mandatory in byte count?. \$\endgroup\$ – insertusernamehere Nov 10 '15 at 19:15

DStack, 7 bytes


I invented the language after the challenge began, but before I see it.

  • \$\begingroup\$ Because it's impossible to prove when somebody saw a challenge, claiming that you didn't see a challenge before you created a language normally doesn't make it eligible. However, since this is a catalog challenges, all languages are welcome, even those created after the challenge, so long as they meet our criteria for being a programming language. Just something to keep in mind for the future :) Welcome to PPCG! \$\endgroup\$ – Mego Nov 11 '15 at 1:06
  • \$\begingroup\$ @Mego I already know that, I wrote that just to mention something (besides I had to write more because the answer was too short). But still thank you! \$\endgroup\$ – DarkPhantom Nov 11 '15 at 1:12

WTFZOMFG, 5 bytes



/        input a decimal number and store it in the cell
 \       print it
  ( )    while the cell is not 0
   \     print it

Aubergine, 33 24 bytes


Aubergine in a nutshell:

Aubergine has four variables and four 2-argument instructions. The variables a and b can be indirected as A and B to point to locations in the program, which can be read and written just like data, making it inherently self-modifying. The other variables are o, which refers to input or output depending on whether it is the second or first argument of the assignment instruction, and i, which is the instruction pointer. The four instructions are assignment (=), addition (+), subtraction (-), and conditional jump (:). The only constant literal available is 1. All variables are initialized to zero.


=Ao                       Set the first character in the program to input character.
-b1                       Set b=-1.
+bi                       Add 6 to b, yielding 5, which is the location of the "1"
=oA                       Output the input value.
=bB                       Set b to the value of where b points, viz. "1"
-bA                       Subtract the input value from b, yield 0 if "1" and -1 if "0"
:Ab                       Conditionally jump to the location corresponding to the input 
                          value, either 48 or 49. Either is past the end of the program,
                          so execution will terminate. This will only happen if b is
                          nonzero, which happens when the input value was not "1".
=ia                       If we made it here, then the input was "1" and now a and b are
                          both zero, just like they were when the program began, so
                          we jump back to just after the input was read and repeat.

Arcyóu, 19 bytes

(?(#(l))(@ 1(p 1))0


(? (# (l)) ; If-statement on the input as int
  (@ 1     ; While 1:
    (p 1)) ; Print 1
  0        ; Else: Print 0

This is actually three bytes shorter than saving it in a variable and while looping it without the if-statement.


Go, 93 bytes

Terribly long.

package main
import ."fmt"
func main(){p:=Println
if a=="1"{for{p(a)}}

Milky Way 1.0.0, 13 bytes



'              # read input from command line
 ?{  ~ ~    }  # if-else statement
   0b          # push 0 to stack and compare to the previous TOS
      !        # output the TOS
        &{ }   # infinite loop
          !    # output the TOS

Milky Way (current version), 13 bytes



./mw <path-to-code> -i <input-integer>

Mouse-2002, 8 bytes



while input():

Java, 95 bytes

class A{public static void main(String[]c){do System.out.print(c[0]);while(c[0].equals("1"));}}

ROOP, 12 bytes



The w operator reads a number from the keyboard because it has an input object above (I). The input object moves to the right and the number created falls down. The X operator removes the input object, the n operator checks whether the number is zero. If the number is zero, the h operator prints the number and ends the program. If it is nonzero, the number moves to the right and the w operator infinitely prints the number.


BotEngine, 24 3x7=21

v 0

The digit 0 is a no-op, allowing me to do stuff like this.


Jelly, 3 bytes


Try it online! (Keep in mind that online interpreters and infinite outputs aren't precisely compatible.)

How it works

  ¿  Convert the two previous atoms/chains into a while loop.
 ¹     Identity function. (condition)
Ȯ      Output/print without newline. (loop body)

DUP, 12 bytes


Try it here!

Anonymous lambda. Usage:





[            {start lambda}
 [$.$]       {output inputnum and check if it's truthy}
      [$.]   {only output inputnum if previous condition is true}
          #  {while-loop previous 2 lambdas}
           ] {end lambda}

Piet, 16 14 codels

codel size 10 for better visibility

enter image description here


       ↑     ↓  
      PSH ← OUN

Old solution (16 codels)

Truth Machine Piet version


             ↑     ↓
            DUP ← OUN

Much simpler than the oddly complicated Piet truth machine on esolangs.org.

Works on PietDev and with npiet 1.3a


Gogh, 8 7 6 bytes

Saved a byte thanks to @ZachGates


Run this in the command line like:

$ ./gogh nio '{ƤØ}?x:' <input>


     Input is implicit
{    Push this code block
 Ƥ    Print TOS
 Ø    Loop forever
?    If STOS is falsy, remove the codeblock from the stack
x    run the code block if there is one, else do nothing
     If there is no codeblock, the program will implicitly output 0

Wierd, 225 bytes

Unlike other languages where the symbols in a program determine which instructions are executed, in Wierd, it is the bends in the chain of arbitrary symbols that determine which instructions are executed.

From the website:

First, a Riddle:
Q: What do you get when you put three marginally-sane programmers on a mailing list with the Befunge and BrainF*** programming languages?
A: You get BeF***, and then they get Wierd.
Chris Pressey then jumped on it, created the angle-to-instruction mapping, and christened the entire mess "Wierd"--a cross between the words "weird" (which the language seemed to be) and "wired" (which would describe the appearance of programs written in the language).

Try it online at http://catseye.tc/installation/Wierd_(John_Colagioia)

0           +  ++++ ++++++++++ ++++
1+  +++ +++  ++  +  +        ++  +
  ++ +  + +  +  +   +        +  +
     +  +  +   +    +          +
      ++++  +++     +     ++  +
        +            +  ++  ++

Come Here, 29 bytes


Befunge, 7 x 2 = 14 bytes

  • \$\begingroup\$ There's a lot of answers in this question so you might have missed it, but for comparison here are the links to two other Befunge answers :) link1, link2 (these are accessible via the leaderboard snippet) \$\endgroup\$ – Sp3000 Mar 30 '16 at 15:38

Pylongolf2, 11 bytes



1           push 1 to the stack
 r          pick a random number between 0 and 1
  0=        push 1 to the stack and compare them
    ?1>~<¿  if true, push 1 to the stack then print it forever.

Oration, 101 bytes

start a function t with x
to iterate, 1
literally, print x
if not x:break#
invoke t with input

Very long. Starts a function called t with arguments x.

Inhale is a command used to keep the program running, you need oxygen to execute. :P

to iterate, starts a while $1 loop, so this becomes while 1:.

literally, print x just prints x, the function input.

if not x:break# is a simple if statement. The # is there because the compiler appends a : to it, so that becomes if not x:break#:. It happens to be golfier than the following good code with normal syntax.

if not x

invoke t with input calls the function.

Transpiles to:

#!/usr/bin/env python3
def t(x):
    while 1:
        print x
        if not x:break#:
t(input("~> "))
  • \$\begingroup\$ Could you include the transpiled source? \$\endgroup\$ – Conor O'Brien Apr 8 '16 at 17:34
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ sure. BTW, there might be a bug about the function call before 2 backtrackings. \$\endgroup\$ – Rɪᴋᴇʀ Apr 8 '16 at 17:42
1 5 6 7 8 9 13

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.