174
\$\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\$
    – Cruncher
    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\$
    – AviFS
    Commented Apr 26, 2020 at 1:42

496 Answers 496

1
13 14 15 16
17
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\$
    – Seggan
    Commented Jul 26, 2022 at 18:32
  • \$\begingroup\$ Thanks, I didn't realize that it was inefficient. \$\endgroup\$
    – Eric Xue
    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\$
    – Jo King
    Commented Feb 16 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
-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\$
    – Cyoce
    Commented Sep 20, 2016 at 17:41
1
13 14 15 16
17

Your Answer

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

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