# Implement a Truth-Machine

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.

# Challenge

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

# Catalog

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.

## 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>

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

# R, 1628 25 bytes

x=scan();while(x)cat(1);0


• this isn't valid, because the 0 will be printed out with an additional [1]  preceding it, and the post states that 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. Mar 3 '18 at 15:24

# Scratch, 12 bytes

I love how Scratch can be so self-explanatory in the right contexts.

• Your list name counts as bytes Jul 11 '16 at 23:36

# Gaot++, 125 bytes

bleeeeeeeeeeet
bleeeet bleeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeet
bleeeeeeeet


Compressed: 11e4e6e13e13e13e13e9e8e6e

Try it online!

# Churro, 100 95 bytes

{========={o}{*}======}{*}======}{={*}{={o}{={o}{={*}{={o}{======={*}{==={*}{======={*}{===={*}


Explanation

Churro is a stack-based esolang where the only syntax element is, well, churros! Or rather, ASCII-art representations of churros. An example of such a churro is {o}====}.

In Churro, each churro has three characteristics:

1. Its orientation; whether it's facing left ({o}====}) or right ({===={o}).
2. Its filling; whether it's filled ({*}==}) or not ({o}==}).
3. Its tail length; the number of =s in the churro is the length of its tail.

Left-facing churros are integer literals; their tail length is their value, while their filling status is their sign. Filled churros are negative, while unfilled churros are positive.

Right-facing churros are operators; their tail length is which operator they represent, according to this table:

{{o}           pop A; discard A
{={o}          pop A, B; push B + A
{=={o}         pop A, B; push B - A
{==={o}        pop A; if A == 0, jump to churro after matching occurrence of {==={o}
{===={o}       pop A; if A != 0, jump to churro after matching occurrence of {==={o}
{====={o}      pop A, B; store B in memory location A
{======{o}     pop A; push the value in memory location A to stack
{======={o}    pop A; print A as an integer
{========{o}   pop A; print A as an ASCII character
{========={o}  read a single character from STDIN and push it to the stack
{=========={o} exit the program


Filled operator churros have the same behaviour, but peek at the stack instead of popping from it.

With that, here's the ungolfed, explained version of the Churro truth-machine:

{========={o}    read char from stdin
{*}======}       push -6
{*}======}       push -6
{={*}            push -6 + -6 = -12
{={o}            pop -6, -12; push -6 + -12 = -18
{={o}            pop -6, -18; push -6 + -18 = -24
{={*}            push input + -24
{={o}            pop -24, input + -24; push input + -48 (convert char to int)
{======={*}      print input as integer
{======={*}      print input as integer
{===={*}         if input != 0 jump back to matching churro


I'm using TheLastBanana's Haskell interpreter to interpret this. Installation instructions can be found there.

Finally, here's the "pure" version (no comments, line length 80, spaces between churros), as output by purify truth.ch:

{========={o} {*}======} {*}======} {={*} {={o} {={o} {={*} {={o} {======={*}
{==={*} {======={*} {===={*}


Saved 5 bytes thanks to Martin Ender!

• And now I want a dulce de leche and some doughnuts... Aug 30 '16 at 23:01

# Moorhen 1 (or original creators version 1 here), 38 bytes

The original language creator has decided to add new instructions, which would change the existing ones. Hence, this language is in Moorhen version one

op pa id el pa id el ai op id ai pi ai


Note this doesn't print if input is 1, because printing only happens at halting, so it just puts infinite ones on stack

## Explanation:

Commands can be (most of) all english words, and the command they execute depends on md5 hash mod 7. I used some length two words that corresponded to each of the seven commands

re: push 0

op: increment ToS

pa: decrement ToS

el: rotate stack (place ToS on BoS)

pi: dupe ToS

id: peek TOS, skip if it is non-zero

ai: flip pointer direction

there are two main segments of code

op pa id el pa id el

ai op id ai pi ai


op pa id el pa id el


This code, when run forwards, will have the pointer leave to the right side, with the initial value on the stack, minus one (0 -> -1, 1 -> 0). When run backwards, with [-1] as stack, it leaves the to the left side with [0] as the stack. When it leaves to the left, it will print the stack, items joined with spaces, so it will print 0. It uses "nops", commands that don't do anything under certain circumstances, or are a pair of inverses.

(the reason the comments look funny is because the interpreter ignores non-words, including real words that are hyphenated)

op pa                nop-when-running-forwards
id el          nop-with-only-one-value-on-stack-and-running-forward
pa       decrement-
id el nop-with-only-one-value-on-stack-and-running-forward
[go to next part of code]


with all these nops forward, its essentially pa when running forward. However, backwards, with -1 on stack:

el                   nop-with-only-one-value-on-stack
id pa             skip-pa,when-TOS-nonzero(-1,is-non-zero)
el          nop-with-only-one-value-on-stack
id pa    skip-pa,when-TOS-nonzero(-1,is-non-zero)
op increment-
[end,print-stack(with,-1,coming-in,print-0)]


With -1, backwards, it's essentially op (then implicit print)

The code that is at the right of that code:

ai op id ai pi ai


given -1, it will just reflect it back. Given 0, it will increment it, then enter a loop of duping ToS, which will be 1.

ai            reflect-pointer-direction-if-TOS-non-zero
op         increment-
id      skip-next-command-if-non-zero. This-command-skips-into-the-middle-of-a-loop:

ai pi ai    this-is-the-loop. pointer-starts-on-pi,because-it-skipped-the-first-ai

Here is a visualisation of how it executes
pi       dupe-TOS (1)
ai    reverse-if-ToS-is-nonzero (it is)
pi       dupe-TOS (1) -again
ai          reverse-if-ToS-is-nonzero (it is)
pi       dupe-TOS (1) -again
...      this keeps happening


# Taxi, 617 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Crime Lab.1 is waiting at Writer's Depot.Go to Writer's Depot:s 1 r 1 l 2 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "z" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 4 l 2 l.[r]Pickup a passenger going to Cyclone.Pickup a passenger going to Post Office.Go to Post Office:s 1 l 2 r 1 l.Go to Zoom Zoom:s 1 r 1 l 2 r.Go to Cyclone:w.Switch to plan "r".[z]0 is waiting at Writer's Depot.Go to Writer's Depot:n 4 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.


Try it online!

There are shorter programs but they kept running out of gas. Here's the ungolfed version:

Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Crime Lab.
1 is waiting at Writer's Depot.
Go to Writer's Depot: south 1st right 1st left 2nd left.
Pickup a passenger going to Crime Lab.
Go to Crime Lab: north 1st right 2nd right 2nd left.
Switch to plan "z" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 4th left 2nd left.
[r]
Pickup a passenger going to Cyclone.
Pickup a passenger going to Post Office.
Go to Post Office: south 1st left 2nd right 1st left.
Go to Zoom Zoom: south 1st right 1st left 2nd right.
Go to Cyclone: west.
Switch to plan "r".
[z]
0 is waiting at Writer's Depot.
Go to Writer's Depot: north 4th left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.


## Thotpatrol, 311 219 bytes

Credit to @MickyT for shaving 92 bytes off

📡JACKING IN📡
💦DM💦 THAUGHTY JO
🕵 📧🍆 JO
🕵 🍑📧 JO
🕵 🍑📧 JO
🎧INTERCEPT MALIGNANT COMMUNICATIONS🎧
🇺🇸REPORT UNPATRIOTIC ACTIVITY🇺🇸


This is a fairly uninteresting truth machine the core structure is as follows:

input a
print a
while a == 1
print a
end while


Here is a link to an implementation in Java: https://github.com/MindyGalveston/thotpatrol-

• what in the world is this language? Sep 4 '17 at 21:06
• This language is a pet project of mine. Its core eccentricity is that there is a finite and non-accessible list of allowed variable names. The only way to programatically allocate data is by abusing string variables and using them as databases or trial and error automatic variable naming which does not have a hard upper complexity limit. Have fun, and I'd love to answer any questions! Sep 4 '17 at 21:16
• How is this 318 bytes? It's 243 UTF-8 bytes, or 172 characters. Sep 4 '17 at 21:30
• Also is Jo or Bo acceptable variable names? Sep 4 '17 at 21:43
• This is what I was trying to say before about a slightly different structure Sep 4 '17 at 23:58

# MATLAB, 39 37 bytes

Two years later, two bytes golfed off.

disp(input('')),while ans disp(1),end


This was a bit shorter than the original one, since it avoid having anything after end, thus saving a comma or semicolon, and it saves one more byte by avoiding the separate call to disp(0).

• Not sure if it worked for older versions of MATLAB but it surely doesn't work for R2019b. Because input('') is used as function parameter it's never saved to ans variable. It works fine for the Octave tho. And for that it can be even shorter: disp(input('')),while 1 disp(1)end works fine. Jun 6 at 20:17

# Duck Duck Goose, 911 bytes

duck duck duck goose

duck

duck duck duck duck duck duck goose

duck

duck duck duck duck duck duck

duck duck duck duck duck duck duck duck duck duck duck goose

duck

duck duck duck duck duck duck duck duck

duck duck duck duck duck duck duck duck duck duck duck goose

duck duck

duck duck duck

duck duck duck duck goose

duck duck duck

duck duck

duck duck duck goose

duck

duck duck duck duck duck duck duck duck duck goose

duck duck

duck

duck duck duck duck duck duck duck duck duck duck duck goose

duck duck duck

duck duck

duck duck duck goose

duck

duck

duck duck duck duck duck duck duck duck duck goose

duck

duck duck duck duck duck duck duck duck duck duck goose

duck

duck duck duck

duck duck goose

duck duck duck

duck

duck duck goose

duck

duck goose

duck duck duck duck duck duck duck duck duck duck goose

duck

duck duck

duck duck goose

duck duck duck

duck goose



Includes 2 trailing newlines. I can't remove the newlines, they are instructions.

5*1 1 5?8-1


Takes input from the command-line arguments. Try it online!

## Explanation

This program consists of eight numbers. These numbers are grouped into instructions; each instruction consists of a label, which is the first number, and zero or more arguments, which follow the label. Instructions with different labels can have different numbers of arguments, but the parsing of instructions happens at execution time (which allows self-modification). The numbers in the program are written to the tape from position 0 at the beginning of the program; each label and argument occupies its own cell, and the instruction pointer occupies the cell at location -1.

5 *
1 1  5
? 8 -1


Dreaderef's preprocessor allows you to write aliases that stand in for numbers representing instruction labels. Using aliases makes the program look like this:

0.   numo  *
2.   deref 1  5
5.   ?     8 -1


(The leading numbers are position labels and are treated as comments.) Before the program executes, * is replaced with the input integer.

0.   numo  *


The first instruction is numo, which outputs its argument (either 0 or 1) in decimal without a trailing newline.

2.   deref 1  5


deref reads the tape at the position indicated by its first argument. It then writes that value to the tape at the position indicated by its second argument. This means that here deref copies cell 1 (the input integer and argument to numo) to cell 5 (part of the next instruction).

5.   ?     8 -1


This instruction is interesting in that the label is dynamically generated by the previous instruction (? is an alias for 0 in Dreaderef, but it is intended to convey that a given cell is uninitialized and will not be read until it is written to). During execution, it will be set to either 1 or 0 depending on the input integer. Proceeding from here requires some knowledge about what labels map to what instructions:

• The instruction with label 0 is end, which terminates execution.
• The instruction with label 1 is deref.

If the input integer was 0, the end instruction causes the program to terminate, and the other two numbers are ignored.

If the input integer was 1, the instruction looks like this:

5.   deref 8 -1


Cell 8 is past the end of the program, meaning that its value defaults to 0. The 0 is copied into cell -1, which is Dreaderef's instruction pointer. This means that execution jumps back to position 0, which is the start of the program. Because * is read before execution of the program, the same input (1) is reused, and the program outputs and loops again.

## Zephyr, 41 bytes

input n
print n
while"1"=n
print n
repeat


Try it online!

A main design goal of Zephyr was that code should be readable and understandable. Looks like this holds true even when the code is maximally golfed. Mission accomplished.

# R, 29 27 bytes

2 bytes brilliantly saved by @Giuseppe

x=scan();while({cat(x);x})1

• the other R solution isn't valid, but there's another two bytes you can squeeze out of this! click here to spoil it Mar 3 '18 at 15:38
• @Giuseppe that is great. Mar 3 '18 at 19:51

# Deoxyribose, 18 bytes

Updated for the new v3 spec

ATGGAGAAGAGCATAAAT


Explanation:

ATG                         ATA (*)
GAG Glu     Dupe            TGG Trp     Power
AAG Lys     Pop             AGA Arg     Unipop
AGC Ser     Jump if <= 0    AGA Arg     Unipop
ATA *                       GCA Ala     Modulo
AAT Asn     Loop            TAA End

• Execution starts at the initial ATG.
• The top element of the main stack is duplicated & printed, then If the value is less than or equal to zero, jump to the ATA formed by the Asn and the start codon (remember, the code is circular), then run through a series of no-ops, including printing some non-printable characters. If the value is greater than 0, loop back to the start.

If you don't like the ugly sequence of no-ops, adding ATG to the end to make the loop target explicit results in a clean termination immediately after the jump, for three more bytes.

Deoxyribose 2, 21 bytes

ATGTGAGAAAAATCTAACTTA


Explanation:

ATG Start                           TAA Stop ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐
TGA Block size = 56               ┏ TGT Cys     Destination of Asn ┆
GAA Glu     Duplicate             ┃ GAG Glu     Duplicate          ┆
AAA Lys     Pop as int            ┃ AAA Lys     Pop as int         ┆
TCT Ser     If >= 0, jump to Thr ┐┞ AAT Asn     Jump back to Cys   ┆
AAC Asn     Jump back to Cys ────┼┘                                ┆
TTA                              └─ ACT Thr     Destination of Ser ┆
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘


This is the first challenge on this site ever answered in this language (since it's only a week old), but I think it's a good showcase of what the language can do so I'll provide a bit of an explanation of what's going on. If you happen to be really interested, the spec, a Python-based interpreter, and additional (less golfed) examples are on GitHub.

Deoxyribose is a stack-based language with a small instruction set and a syntax based on DNA. Execution takes place on a circular stretch of DNA, translating 3-digit "codons" into proteins, each of which corresponds to either

• an operation on one or both of the stacks, or
• a (perhaps conditional) jump to a particular sequence elsewhere in the code.

These jumps can lead to frameshifts, where the read head is moved a non-integer number of codons and the same bit of code ends up doing two totally different things at different times. The degenerate nature of the genetic code makes it possible (and fun!) to use this to your advantage.

• I love this language concept! May 2 '18 at 21:45

## Rockstar, 34 Bytes

Rockstar is a quite new computer programming language, designed for creating programs that are also song lyrics. Rockstar is heavily influenced by the lyrical conventions of 1980s hard rock and power ballads.

Listen to your heart
While your heart is not empty
Scream it


But yes, you are right, it's longer than 34 bytes, but so poetic, I couldn't resist get some lyrics in. You could even sing it!. Here's the golfed version:

Listen to X
Say X
While X
Say X

• Which interpreter are you using? Wouldn't the input be treated as a string, which is truthy? Also, would the Until X loop until X is truthy, rather than while X is truthy?
– Jo King
Apr 30 '19 at 6:50
• @JoKing You are right, the golfed version was incorrect, I changed the Until loop to the While loop. (it did not change the code length). To answer your question, I use my interpreter: github.com/gaborsch/rocky - that worked the expected way, too, so it was my mistake, not the interpreter's. Apr 30 '19 at 7:01
• The input is numeric in this case, so 0 is coerced to false. Apr 30 '19 at 7:03

# Malbolge, 257 bytes

(aONMLKJIHGFEDCBA@?>=<;:98765FD21dd!-,O*)y'&v5#"!DC|Qzf,*vutsrqpF!Clk|ih
gfed9(T&6KoOHZYXWVUTSRQPONM]KJIHGFEDCBA@?>=<;:9876"'~g|edybav_zyxwvotsrq
pSnPlOjibKfedcba_XA??ZYRW:UTSLQ3ONMLK.IHGFE>CBA@?"=<;:38765432s0/.n,+*)
j!&%f{"!~}|_zyxZvYnsrqpRnmlkjML:f_^GF!


Try it online!

From esolangs.org

Quite the abomination, isn't it?

In fact, this language is so horrible, I don't think anyone "programmed" this in the traditional sense. If I'm remembering correctly, this was found by a search program that basically brute-forced for possible Malbolge programs that worked as a truth machine.

• The program was made by esolang's Malbolge expert Malbranche, who is amazing and certainly can program it in other ways than brute force. You may be thinking of the first Malbolge "Hello, world!", which was indeed found by search. May 22 '19 at 4:07
• Ah, yes. Thank you for the correction, it does make sense that a Hello World program would be much longer and more difficult. Sep 27 '19 at 20:21

# Rust compiler (nightly), 86 bytes

#![feature(log_syntax)]macro_rules!t{(0)=>{log_syntax!{0}};(1)=>{log_syntax!{1}t!{1}}}


(playground)

#![feature(log_syntax)]

macro_rules! truth_machine {
(0) => {
log_syntax!(0);
};
(1) => {
log_syntax!(1);
truth_machine!(1);
};
}

truth_machine!(0);
truth_machine!(1);


## Explanation

As the only way to iterate over anything other than the inputs of a macro is recursion, an infinite loop will always end in a stack overflow. I'm considering this error message "constant output of your language's interpreter that cannot be suppressed," as there's no other way to "infinitely" loop. The time for this to occur is dependent on the stack size, and thus most real-world macros will attempt to perform multiple operations per iteration to avoid this. Since this takes more space, I didn't do this. The only ways for a macro to give output are:

• compile_error!, a builtin which will immediately terminate compilation with a message, and is thus not valid for this challenge
• log_syntax!, an unstable builtin which will print its input to the compiler's stdout, with a newline appended
• Returning a value from the macro directly, which directly conflicts with the concept of an infinite loop

I chose to use log_syntax!, as I decided it was the only option that would follow the rules of the challenge. However, it requires a nightly compiler, and 23 additional characters in the source to enable. The syntax of macros is pretty fixed, but one trick I found is that macros called with macro!{} instead of macro!(); do not require a semicolon after, and are thus one character shorter.

# Jasmin, 355 321 bytes

As with the other answers I've written in Jasmin, there isn't a whole lot of golf going on here. This code is (almost) exactly the code obtained from running javap on the class file generated by intrepidcoder's java submission. The one neat golfing trick I found was avoiding the usual .limit locals line by reusing local variable 0.

# Some code golf four years later

1. Shorten the invocation of print by extending PrintStream
2. ldc 2 is shorter than iconst_2
3. Manipulating the stack with dup and swap is shorter than using locals variables with iload_0 and istore_0.

After these changes, the compiled class file needs to be executed with java -noverify.

.class L
.super java/io/PrintStream
.method public static main([Ljava/lang/String;)V
.limit stack 4
getstatic java/lang/System/out Ljava/io/PrintStream;
getstatic java/lang/System/in Ljava/io/InputStream;
ldc 2
irem
dup2
invokevirtual L/print(I)V
dup
ifgt \$-5
return
.end method

• Would it be any shorter to put the code in an initializer block and not have a main method? Nov 3 '15 at 22:44
• @feersum I've never been able to get static blocks to work using java version "1.8.0_60". I think static block are only accepted by java in version 1.6 and earlier. I don't have the correct version to test it so, I'll leave my answer as is for now. Nov 3 '15 at 23:03
• +1 for golfing this 4 years later Aug 27 '19 at 6:21

# Shakespeare Programming Language, 123 120 bytes

T.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Listen tothy.Open heart.
Am I worse you?If solet usAct I.


Try it online!

I make use of a trick to reuse Scene I. For some reason, it doesn’t error to keep taking input, so I do that. Then I just compare the input to zero, and loop if it’s greater. Saved 3 bytes by comparing to I instead of zero because characters initialize to zero—thanks Robin Ryder!

• You can use Is I worse you? instead of Is zero worse you?, since all characters are implicitly initialized at 0. Jan 21 '20 at 14:59
• True true, thank you! Jan 22 '20 at 15:03

# Acrostic, 89 45 bytes

-44 bytes by running the initial input command backwards to output the zero (thanks Jo King for the idea!).

     R
DOUBLE
N  A
PROVIDED
R
I
NIL
T
END
D


Try it online...? (This esolang has no official online interpreter; that link takes you to a repl.it link with my own unofficial Python interpreter loaded in, complete with the truth machine program. If I can find/make a more proper online interpreter, I'll link that instead.)

Acrostic is an esolang designed by Mercerenies for which programs take the form of crosswords, which are traversed word-by-word during program execution.

First, END is run backwards, which starts the program. PRINTED is then run backwards, which will take a numerical input and push it onto the stack. If the top of the stack is 0, the PROVIDED branch is not taken, and instead NIL is run (which does nothing). Because there are no other words to run from there, PRINTED is executed forwards, and then END is executed, ending the program. If, however, the top of the stack is nonzero, the PROVIDED branch is taken, READ is run backwards (outputting the number), DOUBLE is executed backwards (pushing -2), UNO is executed forwards (pushing 1), and PROVIDED is executed (because the top of the stack is nonzero), looping this section forever.

It took me much trial and error to get an Acrostic truth machine this short, though IMHO it is a very clean and compact example. If only this language were easier to golf...

• Thanks for the idea about reusing the read to print the zero @JoKing, I have a 46-byte solution now that I'm playing around with. Oct 1 '20 at 19:58

# Vyxal, 4, 3 bytes

-1 thanks to @Aaron Miller (uses implicit input for the 1s)

[{₴


Try it Online!

• 3 bytes May 17 at 16:12
• @AaronMiller fixed May 17 at 16:27
• Alternate 3 bytes May 25 at 17:35

# Brain-Flak, 6 bytes

{(())}


While the top of the stack is non-zero, push 1. Input to the stack is implicit, and output would also be, but if the program doesn't halt, nothing is outputted. However, one is continually pushed onto the stack, and it's the closest Brain-Flak can get to infinite output.

Try it online!

# Flipbit, 10 bytes

?>>>>>.[.]


Try it online!

# tinylisp, 36 bytes

This is a language that I'm basing an upcoming challenge on. The spec in the challenge doesn't include the disp function, but the reference implementation does.

(d M(q((x)(i x(i(disp x)0(M x))0))))


Defines a function M that takes an argument x (the closest that the language has to input). If x is falsey, we return 0, which is printed. If x is truthy, we want to display x and then recurse. There isn't any equivalent to Common Lisp's progn in the language, so the best way to do this is to use the disp call as the condition of an if. The result is falsey, thus putting the recursive call (M x) in the else branch.

# Sisi, 22 bytes

Sisi doesn't have any way to take user input, so the number is expected to be stored in the variable x (presumably on line 1).

2 print x
3 jumpif x 2


Pretty straightforward: print the number, and keep doing so as long as it's 1.

# Stuck, 9 Bytes

Stuck has a while loop function (which I never added to the docs on Esolangs, but it has existed for a little over 2 months) which makes this possible. It wasn't before this as far as I know :P.

ip"1="'ph

• Dammit I was trying to make a truth machine in Stuck but couldn't figure out how to do it without a while loop Nov 3 '15 at 20:15
• @quartata Sorry about that :P Whenever I get enough free time I will update the documentation.
Nov 3 '15 at 20:20

# Beam, 2523 13 bytes

rSn()>@<
H@<


Try it in the online interpreter! (Warning: it may crash your browser with an input other than 0.)

Beam is a 2D language, based on the concept of a beam of light moving through the 2D source code. Beam is oriented around two main memory values: one held by the beam, and one called the "store". Here are the commands used, in order:

• r - Set the beam to the next ASCII code in the input. (48 for 0, 49 for 1)
• S - Set the store to the beam.
• n - If beam != store, point the beam downward. Does nothing the first time.
• ( and ) - If store != 0, point the beam right/left, respectively.
•  - Decrement the store by 1.

Now, the beam enters () from the left, and bounces back and forth until the store reaches 0. If the store's initial value is 48 (0), it will exit to the left, traveling through these chars:

• n - If beam != store, point the beam downward. This time, since the beam is 48 and the store is 0, it does its job.
• < - Unconditionally point the beam to the left.
• @ - Output the beam as an ASCII character. Prints 0.
• H - Halt the program.

However, if the store's initial value is 49 (1), it exits the loop to the right, and runs through this code:

• > - Unconditionally point the beam to the right.
• @ - Output the beam as an ASCII character. Prints 1.
• < - Unconditionally point the beam to the left.
• @ - Output the beam as an ASCII character. Prints 1.
• > ...

...and so on until the end of time (or until your browser crashes).

Thanks to @MickyT for this awesome layout!

• +1 I like it, didn't think I could shorten it, but here's a slightly shorter version. 2 Lines rSn()>@< and H@< for 13 Nov 3 '15 at 22:16
• @MickyT Holy cow, that's brilliant! I'll update in a sec Nov 3 '15 at 22:18

# JavaScript (ES6), 777364 61 bytes

x=prompt()==1;j=a=>{if(x)setTimeout(j,9);console.log(+x)};j()


Explanation:

x = prompt() == 1;             // this makes sure input is 1 or not while defining
j = a => {                     // es6 arrow function
if (x)                        // if x is 1
setTimeout(j, 9);            // make sure to do this function again in 9ms
console.log(+x);              // log the number
};
j();                           // call j

• Better version: x=prompt()==1;j=()=>{if(x)requestAnimationFrame(j);console.log(x?1:0)};j() Nov 3 '15 at 19:53
• Even better, replace j=()=> with j=a=> Nov 3 '15 at 19:59
• Actually, using x=prompt(); is shorter, but you have an x==1?1:0 that could just be x. That leaves x=prompt();j=a=>{if(x==1)requestAnimationFrame(j);console.log(x)};j() at 69 bytes. However, instead of using requestAnimationFrame you could use a setTimeout, which is shorter and leads to x=prompt();j=a=>{if(x==1)setTimeout(j,10);console.log(x)};j() at 69. Oh crap! That would mean that JS beats Stack! D: Nov 3 '15 at 20:12
• Haha. The reason I use x==1?1:0 is so that if the user inputs "true" it counts as 0. Nov 3 '15 at 20:50
• (oh my, it's liam4! hey!) But you don't need to. The only inputs needed 1 and 0. Nov 3 '15 at 21:01

## Brainfuck, 54 bytes

+++[>++++[>++++<-]<-]>>>,.[>+<<[>>-<<-]>>>+<<-]>[>.<]


Explanation:

+++[>++++[>++++<-]<-]>>> Set a register to 48 (ASCII 0), using multiplication to reduce the byte count (3*4*4), then set the pointer to the next instruction

,. Receive and print a line of input

[>+<<[>>-<<-]>>>+<<-]Set the next register to be a numerical value, and the one after to represent the ascii output value

> Move the data pointer to the numerical register

[>.<] While the numerical register is not 0, print the ascii register

• I already have a shorter BF program, but just so you know, 48 can be made shorter. See this helpful page. Nov 3 '15 at 21:44
• Thanks. Yeah, I didn't see your program before I posted mine, must have missed it when scrolling through. Nov 3 '15 at 22:01
• Try running the code snippet contained in the question. Nov 3 '15 at 22:12

# brainfuck, 20 bytes

,[.>+<-[-[>]<++<-]>]


This requires an interpreter that exits with an error upon stepping out of bounds with < (such as this one). Stepping over the left edge in case of an even value was the easiest way I found to do a parity test. I wouldn't be surprised if it could be a couple of bytes shorter.

# Batch, 44 bytes

@set/p n=
:a
@echo %n%
@if %n%==1 goto :a


## Explanation

• set /p reads from stdin into a variable
• :a is a GOTO marker, because batch does not have while loops

The rest should be obvious: output the variable n and if n` is 1, repeat.