178
\$\begingroup\$

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.

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>

\$\endgroup\$
19
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ Commented Nov 3, 2015 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ Commented Nov 3, 2015 at 17:38
  • 5
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Commented Nov 6, 2015 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Commented Nov 10, 2015 at 1:13
  • 1
    \$\begingroup\$ Is one allowed to print an infinite number of 1s? That is, not print out 1s forever, but print out an infinite list of 1s all at once? This would be theoretically demonstrated, but the language has no notion of printing more than once. It just generates an output. So is it okay if it runs indefinitely, but would print infinite 1s given infinite time (to finish executing)? \$\endgroup\$ Commented Apr 26, 2020 at 1:42

509 Answers 509

1
13 14 15 16
17
0
\$\begingroup\$

INTERCAL, 41 bytes

Based on answer by @unrelatedstring. If you don't care for errors, won't you guys golf off the program easily?

DOWRITEIN.1DOCOMEFROM.1(1)PLEASEREADOUT.1 

Try it online!

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

Batch, 28 bytes

:1 @Echo(%1&Goto:%1 :0 

uses input as output and script flow controller.

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

Add++, 7 bytes

+? Dx,O 

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ doesn't seem to work anymore but here is a 9 byte \$\endgroup\$ Commented Jan 4, 2022 at 22:54
0
\$\begingroup\$

SMALL, 14 bytes

$->x{x=1?1!}0! 

Ungolfed code:

$ -> x { x = 1? 1! } 0! 

We first read from stdin and store the input in x, with the following line.

$->x 

We then enter an iteration, where we first compare if x is 1. If that's the case, we print 1. Since this check will never be false, this iteration will be infinite.

{ x = 1? 1! } 

If the condition in this iteration is false, the entire iteration stops and we go to the last line, which prints a single zero after which the program halts.

0! 
\$\endgroup\$
0
\$\begingroup\$

A0A0, 67 bytes

I0S1M2V0G0 G-1G-1G-1G-1 O0 A0A0 A0C3G1G1A0 A0O1A0 A0A1G-3G-3A0 G-3 

The top line takes input, then adds one to this number and multiplies it by two. For input 0 we now have 2 and for input 1 we have 4. This is used as the offset for the goto instruction. If we jump by two we end up at line three which prints zero and halts. If we jump by four, we get to line five and get to an fininite loop.

A0 A0 A0 C3 G1 G1 A0 A0 O1 A0 A0 A1 G-3 G-3 A0 G-3 

This infinite loop simply prints one (on the third line in the loop: O1).

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

Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes

?x(; 

See the README to see how to run this

The ? could be replaced with a ! for the same effect.

?x(; # The program ? # If x # The input is truthy (i.e. 1) (; # Print the input forever # Otherwise print the condition (which was 0) 
\$\endgroup\$
0
\$\begingroup\$

Python, 59 43 bytes

if input()=="1": while 1:print(1) print(0) 

-16 by Seggan

\$\endgroup\$
2
  • \$\begingroup\$ This can be significantly golfed: no need for explicit exit(), and the i variable can be inlined. \$\endgroup\$ Commented Jul 26, 2022 at 18:32
  • \$\begingroup\$ Thanks, I didn't realize that it was inefficient. \$\endgroup\$ Commented Jul 27, 2022 at 0:03
0
\$\begingroup\$

ArcPlus, 22 bytes

(: n (,))(@ (p n) (p n 

Verbose version:

(set n (input)) (while (print n) (print n)) 
\$\endgroup\$
1
  • \$\begingroup\$ Link to language is dead \$\endgroup\$ Commented Oct 1, 2020 at 22:26
0
\$\begingroup\$

nroff/troff, 27 bytes

Ties with user100411's 27 bytes answer. This version, however, does REALLY outputs 1's FOREVER for input 1, while previous version halts by stack overflow.

.de a \\$1 .while \\$1 1 .. 

Try it online!

Usage

.a 0 .a 1 
\$\endgroup\$
0
\$\begingroup\$

Thunno, \$ 6 \log_{256}(96) \approx \$ 5 bytes

(actually 4.94 bytes, but the leaderboard doesn't take floats)

!)[1ZK 

(No ATO link since that's on an outdated version)

Explanation

!)[1ZK # Implicit input ! # Push `not input` (i.e., 1 if input == 0; 0 if input == 1) ) # Break if the top of the stack is truthy (i.e. input == 0) # Since the stack is filled with 0s at the start, 0 is implicitly output in this case [ # while True: 1ZK # print 1 
\$\endgroup\$
0
\$\begingroup\$

Desmoslang Assembly, 12 Bytes

7+2*IJTGE1TO

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

x86 machine code, PC DOS, 10 bytes

00000000: a082 00cd 293c 3174 fac3 ....)<1t.. 

Listing

A0 0082 MOV AL, DS:[82H] ; AL = first char from command line DISPLAY: CD 29 INT 29H ; DOS fast write AL to console 3C 31 CMP AL, '1' ; was input a '1'? 74 FA JE DISPLAY ; if so, loop "forever" C3 RET 

Sample output

A standalone DOS .COM program.

A>TRUTH.COM 0 0 A>TRUTH.COM 1 111111111111111111111111111111111111111111111111111111111111111111111111111111 111111111111111111111111111111111111111111111111111111111111111111111111111111 111111111111111111111111111111111111111111111111111111111111111111111111111111 111111111111111 (ended because Ctrl-Break was hit) 

Note: shouldn't ever crash or run out of memory since no memory is used. More likely it'll just burn a permanent screen full of 1's onto your IBM 5151 monochrome CRT monitor (so in a sense it will run forever).

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

AArch64 machine code + Linux syscalls, 40 bytes

00: 528007e8 mov w8, #63 // read() 04: 2a1f03e0 mov w0, wzr // 0 = stdin 08: 910003e1 mov x1, sp // to stack 0c: d2800022 mov x2, #1 // 1 byte 10: d4000001 svc #0 // syscall, should mov x0, #1 14: 394003e9 ldrb w9, [sp] // load byte 18: 52800808 mov w8, #64 // write() 1c: d4000001 svc #0 // syscall, w0 = 1 = stdout 20: 3707ffe9 tbnz w9, #0, 1c // loop last instruction if byte & 1 24: d65f03c0 ret 

Can be used as a void (void), or an int (void) such as main(), returning 1. If you want to use it as _start() without segfaults, replace the ret with:

24: 52800ba8 mov w8, #93 // exit() 28: d4000001 svc #0 // syscall 
\$\endgroup\$
0
\$\begingroup\$

(,) i 140 85 29 Chars or \$29\log_{256}(3)\approx\$ 5.75 Bytes

(,,((()),()),,((()),())(),()) 

TIO

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

ForWhile, 28 bytes

ForWhile does not have infinite loops, so to output indefinitely the program has to continuously copy its source code behind the instruction pointer.

_:49=[{}1+20[:@;20-$1-:)'#]#

online interpreter

Explanation

_ \ read a character from standard input :49= \ check if it is one [ ]# \ if the character is not one, print it {}1+20[:@;20-$1-:)'# \ infinite 'loop' {} \ get the current instruction pointer (empty procedure) 1+ \ offset instruction pointer such that it points to start of code block 20[:@;20-$1-:) \ copy code starting at { to position after # '# \ print the second value on the stack (the character read from standard input) 

ForWhile, 42 bytes

This version has constant memory usage

_:49=[34(!;$1-]{}10+:34[:@;34-$1-:)49#$.]#

it works similarly to the shorter version, but additionally deletes the old code and cleans up the stack

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

Racket, 58 bytes

#!racket (let l([n(read)])(print n)(if(= n 0)(void)(l n))) 

Try it online!


Explanation

Our program creates a recursive named let statement that loop if n is not equal to 0. On the first iteration, we read user input into n. We print ns value and test whether we should loop or not.

#lang racket (let loop ([n (read)]) (print n) (if (= n 0) (void) (loop n))) 
\$\endgroup\$
0
\$\begingroup\$

Intcode, 19 bytes | 8 ints

Everyone's favorite intcode computer from the Advent Of Code 2019.

3,0,4,0,1005,0,2,99 
\$\endgroup\$
0
\$\begingroup\$

*><>, 11 bytes

Takes input through the -i flag

:?`n; !`:n 

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ ... wouldn't just v and > work better than using dive (though that ends up identical to a normal ><> solution)? also, you can move the last n to the start of the line \$\endgroup\$ Commented Feb 16, 2024 at 22:30
0
\$\begingroup\$

Boo, 34 bytes

def f(x): print x;while x:print x 

Boo is a language inspired by Python and implemented in .NET. Its syntax is very similar to Python 2's.

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

ibe, 18 bytes

addsQakqasQshQmqmq 

explanation: (ibe doesn't support comments so this code is not valid)

ad | initialize 1 item in tape: Q dsQ | get input and set it to Q akq | point 0 (aka 'q') asQ | print Q shQmqmq | if Q is not equal to 0, go to point 0. (aka, if input is 1 then it will loop forever) 
\$\endgroup\$
0
\$\begingroup\$

punchcode, 16 9 bytes

hexdump:

00000000: 16 01 05 1A 1D 0B 11 1E 0D | ......... 

uncompiled:

-START | ---O-OO-| -------O| -----O-O| ---OO-O-| ---OOO-O| ----O-OO| ---O---O| ---OOOO-| ----OO-O| 
\$\endgroup\$
0
\$\begingroup\$

Hatchback, 32 bytes

0 0 0 16 0 1 0 6 0 65281 1 65535 

asks for input, prints, checks if its 1 and if it is continue printing.

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

Bespoke, 48 bytes

truth:a machine?fiction or fact answer:i am true 

This is adapted from an example program I bundled with the source code of the official interpreter, but without the trailing CONTROL END (because it's not needed!).

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

marb, 21 19 bytes

+ \?_ -^[ [n. .n= _ 

The spaces are represented as n (a.k.a NOP). Also i implemented a feature that just jumps to the the nearest _ in the y-axis. that removes two bytes from the program

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

SAKO, 68 bytes

CZYTAJ:I GDYI=0:1,INACZEJ2 2)TEKST 1 SKOCZDO2 1)TEKST 0 STOP1 KONIEC 

I believe this to be an optimal solution.

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

'Python' is not recognized, 17 15 14 bytes

0@?[0|;]jl1|jl 

Input "0", Input "1" or anything else

Explanation

0@ " Pushes zero then the input to the stack " ?[...] " Checks if the two TOS's match, if it is... " 0|; jl..jl " ...print 0 and halt, else enter the loop that... " 1| " ...prints the number 1 " 
\$\endgroup\$
0
\$\begingroup\$

True, 19 15 bytes

, :``:.(0=)(|)? 

assumes if user inputs a 0 or a 1

\$\endgroup\$
-1
\$\begingroup\$

Ruby, 22 bytes

->(n){n==0?0:loop{p1}} 
\$\endgroup\$
-2
\$\begingroup\$

Python 2, 43 42 41 bytes

x=raw_input();print x while x>'0':print x 

Got a syntax error at the while loop if I tried to run it as a one-liner. Not really sure why.

EDIT: Knocked off a semicolon.

Knocked off ANOTHER semicolon that I put on there because I've been looking at C too much lately.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ You could use x=input() and then x>0 \$\endgroup\$ Commented Sep 20, 2016 at 17:41
1
13 14 15 16
17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.