# 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

• 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

# VBA, 54 48 Bytes

Sub f(u):Do:Debug.Print u:Loop While u>0:End Sub

Look Guys, VBA can fit on one line(almost) and be hard(ish) to read like all the other Languages.

Debug.Print could be Msgbox but I feel that isn't the Spirit of the challenge and you really don't want Never ending pop-ups

Old Code

Sub f(u):Do:Debug.Print u:If u=0 Then End
Loop:End Sub
• Using ActiveSheet.Range("A1") as your input and running in the Immediate Window, you can reduce to 31 bytes: ?[A1]:Do Until[A1]=0:?[A1]:Loop May 9 '18 at 9:40
• For sure. Any of my VBA answers are designed not to run in immediate and do not use sheets. VBA can for sure be shortened by using those methods and I encourage you to explore the possibilities. But at the time there were few to no VBA responses so I limited myself to Subs only. May 9 '18 at 10:15

## FORTH, 44 bytes39 bytes 31 bytes

Edit:

As suggested by @Nate Eldredge, we can shorten the code, if we allow extra spaces in the output. This program is 31 bytes long:

: P BEGIN DUP . ?DUP 0= UNTIL ;

Sample run:

1 P
0 P

First version:

: P BEGIN DUP 48 + EMIT ?DUP 0= UNTIL ;

Sample run:

1 P
0 P

Explanation:

We expect the value 'b' of 0 or 1 on the stack.

: P       -- beginning a word P                          ( b )
BEGIN     -- starting a loop                             ( b )
DUP 48 +  -- creating an ASCII code for the character    ( b  b+48 )
EMIT      -- echoing the character                       ( b )
?DUP      -- dup'ing the value if non-zero               ( 1  1 ) or ( 0 )
0=        -- testing if the value is zero                ( 1 FALSE) or ( TRUE )
UNTIL     -- end of the loop if true                     ( 1 ) or ( - )
;         -- finishing the word

If I take the challenge seriously, FORTH has Standard I/O capabilities, but it is natural in FORTH to take the input from the stack.

If I use the STDIO feature, the code looks like this (44 bytes)

: P KEY BEGIN DUP EMIT DUP 48 = UNTIL DROP ;

Sample run:

P

(Note, that in my environment the standard input was buggy)

• My FORTH is rusty, but wouldn't it be easier and shorter to use . instead of 48 + EMIT? Nov 5 '15 at 19:45
• @NateEldredge . puts an extra space after the number, otherwise it's OK. I've read in some answers that it may be acceptable. If that's the case we can shorten the code. I'll update the answer. Nov 5 '15 at 23:12

## MIPS asm, 24 bytes

main:
li $v0, 5 # load read int syscall # exec read int, stores value in$v0
move $a0,$v0  # store in $a0 li$v0, 1  # load print int
loop:
syscall  # print $a0 bgtz$a0, loop  # loop while $a0 is greater than zero Had to learn MIPS recently, might as well do something fun with it. ## C, 35 chars main(c){for(gets(&c);c%puts(&c););} This is even hackier than cbojar's solution, from which I copied the abuse of the parameter c (int used as char[4]), along with the reliance on little-endian. puts returns a non-negatve number on success, which (on my Linux/gcc4.8.2) happens to be the number of bytes printed, which happens to be 2. c%2 tests if c is odd, which is true for '1' and false for '0'. # Marbelous, 23 This version doesn't terminate after the zero is printed, but that should be alright: ..}0 ../\// >0 }0 +O +O Old version: }0@0 \\ ../\+O >0\/+O @0 It doesn't add a newline between each 1, but whatevs. • You need to terminate if your language is at all capable of terminating. Nov 18 '15 at 3:31 ## O, 14 bytes i{1{1o1}w}{0o}? O is a work-in-progress language with loads of commands and an interpreter written in "APL-style C", which means incomprehensible code. i Get input as String { Start a CodeBlock (like ruby) 1 Push 1 to the stack { Start a CodeBlock 1 Push 1 to the stack o Pop the stack and print it 1 Push 1 to the stack } Push the CodeBlock to the stack w Do the CodeBlock on the top of the stack while the value under it is true. (Pops them both.) } Push the CodeBlock to the stack { Start a CodeBlock 0 Push 0 to the stack o Pop the stack and print it } Push the CodeBlock to the stack ? If the 3rd down value in the stack is truthy, do the CodeBlock 2nd down in the stack, otherwise do the CodeBlock on the top. (Pops the first 3 values on the stack.) • "APL-style C" - you mean nightmares? – user45941 Nov 15 '15 at 5:07 • @Mego yep, pretty much Nov 15 '15 at 5:14 • I think you're being unfair to APL. Nov 16 '15 at 1:20 • @ThomasKwa it's a direct quote. Nov 16 '15 at 19:41 • @Hipe that is horrible. must it be golfed? – cat Jul 22 '16 at 11:18 # Python 2- 64 bytes x=input() if x==0:print"0" elif x==1: while True: print"1" • A trick you can exploit in Python is that 0 is the same as False and anything but 0, including 1, is True. This generally holds in most programming languages Nov 1 '16 at 20:00 # Jolf ## 0 Bytes I found out what to do with the zero-byte program! I made a truth machine. 0 as input 1 as input • Congrats, you have made the most boring answer on this challenge! ಠ_ಠ +1 Jan 16 '16 at 18:13 • @zyabin101 bows thank you. Jan 16 '16 at 18:13 • This appears to be invalid as the second 1 seems to be a 3. Apr 17 at 2:48 • @Makonede It worked 5 years ago. Quite frankly I'm not sure what changed. Apr 17 at 4:22 • @ConorO'Brien Based on the JS code I figure it's just a bug. Still though, quite strange Apr 17 at 18:06 ## Java, 87 bytes interface A{static void main(String[]a){System.out.print(a[0]);main(a[0].split("0"));}} (has output to STDERR, but that should not matter) • I'm not entirely sure if this is valid. The rules state that the program must infinitely run unless killed or out of memory. This will cause a stack overflow, since Java doesn't have tail call recursion optimization. – user45941 Jan 25 '16 at 13:31 • Yes, for the standard JVM; but there the size of the stack depends on the memory allocated. If the memory allocated by -Xss is large enough, it will run arbitrarily long (see also stackoverflow.com/questions/4734108/…). The stack overflow therefore is just the visible result of the program being out of memory. Jan 25 '16 at 13:36 • @SeanBean "take input from STDIN or an acceptable alternative" - command-line arguments are an acceptable input method. – user45941 Sep 1 '16 at 9:27 • maybe downvote the challenge if you don't like it, instead of this particular Java answer? Not that I mind but you could reach a larger audience there... downvoting because you believe an answer is the shortest kind of defeats the purpose of codegolf?? Sep 7 '16 at 18:28 • A stack overflow is a form of memory outage: there is no more place in the stack memory for another stack frame. Jan 10 '19 at 9:55 # Detour, 2 bytes ,~ Try it online! , will print a value then push it to the next cell. ~ is a filter, so it will push a value IFF it is greater than 0. Cells wrap around the edges. # HALT, 49 bytes 1 IF '0' 2 ELSE 3 2 TYPE '0';HALT 3 TYPE '1';SET 1 Pretty simple. If input is one go to 3, output 1, set the pointer to 1 so the program never ends. If input is output 0, print, then halt. Online interpreter (Firefox only) • such amazing much wow where's rightgoat Feb 23 '16 at 3:12 • @Seadrus ---I ate him---. I mean, he'll be coming soon Feb 23 '16 at 3:12 • No he won't, you're the only goat left ;) Feb 24 '16 at 3:12 # Shtriped, 33 bytes e : t : . d : i : p : . . p : This prints the 0 or the infinite stream of 1's without any trailing newlines or spaces. Explanation: e : \ initialize a variable named ":" t : \ prompt for integer input, storing the result in : . \ define a function named "." that will only return if : is 0 (the next 4 indented lines are part the function) d : \ decrement : if : is positive, else return immediately i : \ : must have been 1 to reach here and was just decremented, so increment back to 1 p : \ print :, which we know is 1 . \ recursively call ., endlessly looping . \ call . initially p : \ if . terminated this line will finally be run, printing : which we know is 0 ## BASTARD, 83 bytes {{fi in 0{!b {= {t 0} ‘1’} {(o <> {{fi out ‘1’}{o}}){o}}{fi out ‘0’}}}} Note: This language is not qualified. Mostly because I'm still designing it. I just wanted to test drive it against some puzzles. Explanation: fi in copies the input into the 0 place on the Variable Stack. !b is a basic if statement to check if its a "1" or not. If it is, we just use fi out to print our "0". Otherwise, we define a new function called o that prints a "1", and then calls itself again. • Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a great first answer, +1. Your language looks interesting; once you've got enough reputation you could get help developing it on Chat. Feb 19 '16 at 15:05 # NTFJ, 27 bytes :*:##~~~~~#@|########@|($~^

An online interpreter can be found here.

NTFJ is an esoteric programming language, made by user @ConorO'Brien, that is intended to be a Turing tarpit. It is stack-based, and pushes bits to the stack, which can be later coalesced to an 8-bit number.

• The only pushable values are 0 with ~ and 1 with #.
• The only manipulations possible to the actual values of the stack are to wrap eight bits into a byte with @, and to NAND with |.
• The only logic command is IF with (), but combined with JUMP ^, it can be used to create loops.

Thus, it's quite difficult to manipulate values to do your bidding.

### How it works

Implicit input: byte 48 for 0 or 49 for 1.
:*:                            Duplicate the top item, pop/output, and duplicate again.
##~~~~~#@|                  Push 193 and perform NAND.
########@|        Push 255 and perform NAND.
These two operations change 48 to 0 and 49 to 1.
(       If the top item is not 0:
$Pop the top item. ~^ Push 0 and jump to that instruction. This effectively creates a while loop that loops the entire program. • I believe removing the last paren should still work. Mar 2 '16 at 19:42 • @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, it does! Mar 15 '16 at 20:08 # Beatnik, 26 bytes J ZD ZD JA K ZZZZJ Z JJ MF An explanation Words Scores Action J 8 Get character value from input ZD 12 Duplicate TOS ZD 12 Duplicate TOS JA 9 Output TOS character K ZZZZJ 5 48 Push 48 (char 0) onto stack z 10 Pop 2 from stack and subtract JJ MF 16 (7) If not zero skip back 7 words Of course something like the following, while still not making sense, looks more like what you would expect for a Beatnik program. Shall falsey determine truths? We **WithoutAWarningAboutMemoryUse** printed infinitely yeas! • The last one mostly makes sense, except for He quackpizzled? :) Mar 16 '16 at 22:50 • @ETHproductions Yea, try to find a word that is SORTAWORDLIKEWITHABIGNUMBER and still fits gets difficult :) Will have a play and see what I can come up with. Mar 16 '16 at 22:55 • @ETHproductions That's a bit better now Mar 16 '16 at 23:08 # Lua, 56 52 Bytes I know that this answer in 70 Bytes exists, but its author doesn't look like he's updating it when someone point out an improvement. if io.read'*n'>0then::a::print"1"goto a end print"0" Old 56 bytes solution if io.read()=="1"then while""do print"1"end end print"0" Nothing special here, just using the fact that "" evaluates to true to save a byte on the infinite loop. Parenthesis for functions parameters aren't mandatory when they only take a single string, which is not stored in a variable. # Julia, 51 45 bytes readline()>"0"?while 2>1 print(1)end:print(0) Read a string from STDIN. If it's lexicographically larger than the string "0" then print 1 forever, otherwise print 0 and we're done. Saved 6 bytes thanks to Sp3000! # UGL, 6 bytes il$o:o

Try it online!

How it works:

i       #stack.push(input)
l  :   #while stack.peek():
$# stack.dup() o # print(stack.pop()) o #print(stack.pop()) # PowerShell, 24 bytes 'for(){1}'*"$args"+0|iex

Generate expression as string and pass it to Invoke-Expression (eval).

It casts $args array to string with "", then multiplication sign casts it to int and string for(){1} is repeated int times (1 or 0 - empty string). Then we add 0 to this string, which will be cast to a string also. Resulting string expression (for(){1}0 or 0) is then piped to Invoke-Expression, resulting either in endless loop outputting 1 or one-time output of 0. # WistfulC, 141 bytes This C has seen better days. if only int n were 0... wish for "%d",&n upon a star someday !n... wish "1" upon a star *sigh* wish "0" upon a star if wishes were horses... Obviously not competitive, but then neither is this language. Rough translation to regular C: int n = 0; scanf("%d", &n); while (n) { puts("1"); } puts("0"); exit(0); ## Silicon, 3 bytes I[] Explanation: I Get input [ While the top of the stack is 1 Implicit output ] End while Implicit output # T-SQL 23 bytes No STDIN here so a hard-coded variable. DECLARE @ INT =1; or DECLARE @ INT =0; and the truth machine is l:PRINT @ IF(1=@)GOTO l # C, 41, 40 bytes main(c){for(c=getchar();putchar(c)&1;);} Reads a single character from stdin, writes to stdout. This version is 1 byte longer than feersum's solution, but removes his/her assumptions onstdin. • Would putchar(c)&1 work? Aug 29 '16 at 16:41 • Yes, you are right! One byte saved, thanks @Dennis. Aug 29 '16 at 16:51 ## PHP, 34 bytes <?for($f=fgetc(STDIN);\$f;?>1<?)?>0

Wanted to try to get rid of the print but not sure it's worth it since you have to reintroduce the <? tags

# Java, 143141125 88 bytes

interface T {static void main(String[]a){System.out.print(a[0]);main(a[0].split("0"));}}

# Ungolfed Test Code

interface T {

static void main(String[] a) {
System.out.print(a[0]);
main(a[0].split("0"));
}
}
• That's 143 characters. Sep 1 '16 at 8:49
• Why did you even check? Sep 1 '16 at 8:51
• I'm using a userscript for PPCG, and it tells me how many bytes there are. (You should totally use it, it's worth it) Sep 1 '16 at 8:54
• Ahh ok. It's shorter now anyway :P Sep 1 '16 at 8:55

## dc, 13 12 bytes

?[pd1=@]ds@x

Run:

dc -f truth_machine.dc <<< "1"

Adding to the diversity of languages used, I present a dc solution that works as follows:

?              # reads the input and pushes it on top of the stack
[pd1=@]ds@x    # stores the macro command [pd1=@] into register '@' and executes it
p           # prints the value on top of the stack
d           # makes a duplicate that is pushed on top
1=@         # pushes 1, pops two numbers and if they are equal, the macro from
#register '@' is executed (again), thus making an infinite cycle

## Lua, 34 Bytes

repeat print(arg[2])until arg[2]<1

arg[2] contains the first command line argument, (arg[1] contains the filename)

Give an input through the command line, and it shall spam it if it's 1, or once if it's not.

Simple enough.

## Copy, 67 59 bytes

My new esolang :D

getch a
print a
skip b
skip 1
copy -4 0 1

Explanation:

getch a     Take input in variable 'a'
add b a     Set 'b' to 'a'
add b -48   Substract 48 from 'b'
print a     Print 'a'
skip b      Skip the copy if 'a' is not zero
skip 1      ^
copy -4 0 1 Copy the code block from the print to this instruction after this instruction
• protip: *subtract Sep 25 '16 at 9:22
• @DestructibleWatermelon No Sep 25 '16 at 9:26

# Crystal, 4837 36 bytes

y=gets;y=="0\n"&&(p 0;exit);y=="1\n"&&loop{p 1}
y=gets;y=="0\n"&&(p 0;exit);loop{p 1}
y=gets;y=="0\n"&&(p 0;1/0);loop{p 1}

Edit: Shaved off 10 bytes because the post doesn't specify what should happen on invalid input (like 2). If it does and I misunderstood, let me know.

Edit: Shaved off 1 byte by dying with an error instead of normal exit.

Crystal is statically typed, so I couldn't just do gets.chomp (gets can return nil, and nil doesn't have chomp). The alternative was gets.try &.chomp, but that takes much more space than just having the newlines.

In Crystal (and Ruby) you can do something like puts 0 if y=="0\n", however you can also shave off 2 bytes by doing y=="0\n"&&puts 0 as the && operator returns the last object it tests for truthiness.

loop is a method in the standard lib that infinitely runs the block. It's a much shorter way of writing while true;CODE;end.

p prints the result of .inspect on its arguments to the output. Here I abuse it as a shorter puts because for numbers it'll just return the number.

# Valve scripting language, 38 bytes

alias 0 echo 0
alias 1 "echo 1;wait;1"

This defines two commands, 0 and 1. Type 0 into the console for the zero case, and 1 for the 1 case.

• Could I just try this in half life's console, or do I need the source SDK? Dec 21 '16 at 1:56
• @Pavel I tested it on the TF2 console, so that should be fine. Dec 21 '16 at 2:02