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

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

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

## Javascript (Node), 40 bytes

for(;console.log(v=process.argv[2])|v;);

In Javascript for the browser this can be 29 bytes

• Welcome to PPCG! – Martin Ender May 7 '17 at 20:51

# Triangular, 6 bytes

$.(]%< Try it online! This formats into the triangle:$
. (
] % <

The commands that are executed (without control flow) are $(%]. Pretty simple. •$ read input as integer
• ( open loop
• % print as integer
• ] jump back to loop if top of stack is truthy

# ILL, 19 bytes

/RnN~
>1nR\
\   /

ILL (inverse linear law) is new right now, so this represents virtually all the instructions/groups of instructions it has at the time of posting this. The main idea though, is that the program is run by light, which reflects off of mirrors and decrease in intensity as it moves on (obeying the inverse linear law, because its 2d). Data is primarily stored in the intensity of the light, which can sort of be used as a control structure, since light with an intensity < .5 dims and does not move on to the next tick. This means that different intensities of light move different lengths. This program utilizes the dimming behavior to either halt after printing 0, or prints 1 and continues. Basically, it takes a numerical input (side note: instructions that set intensity actually do so after the current tick has run, and they also persist the light over to the next instruction, no matter what intensity it has), prints it, and then re-intensifies and enters a loop. However, the light is only re-intensified if it reaches the re-intensify instruction, which light with an intensity of 0 will not. More detailed explanation (also a valid ILL program):

/RnN~
>1nR\
\   /
#END OF FILE#
Truth machine.

~ : emits light horizontally at the start of a program.
N : takes numerical input, set light intensity to the input.
n : produces numerical output. If the light has an intensity of 0 here, it will dim after n outputs and not move on.
R : re-intensify, if the light made it here, it can now continue into the loop.
> : double/splitting mirror, allows the light from the above / mirror to enter the loop and move right.
1 : set intensity to 1.
n : numerical output.
R : re-intensify.

the remaining \, /, and \ reflect the light back to > where it can start the loop again

# C# (.NET Core), 80 79 bytes

class p{static void Main(string[]I){do{Console.Write(I[0]);}while(I[0]=="1");}}

Try it online!

I've seen some disagreement about whether arguments count as STDIN. "No" seemed more popular, but if it were acceptable then this would save 15 bytes over the previous C# answer.

Saved 1 byte by removing an unnecessary space

# Ly, 7 bytes

n:u[:u]

Explanation:

n        # take input
:u      # duplicate it and print it
[     # while the top of the stack is not 0...
:u   # duplicate it and print it
]     # end loop

# Cubically, 6 bytes

According to the spec, this should work:

$(%7)7$      - Get user input as number (either 1 or 0, according to the rules)
(  )7 - do ... while input value is nonzero
%7   - Output the input as a number

However, TIO seems to continue the loop even if the input is 0. The Lua interpreter handles it correctly, though.

• $:7(%7)6 works on TIO for now. It should behave identically (instead of looping based on the value in 7, it sets 6 to that value and loops on that) but it doesn't, meaning there's a bug in the interpreter. – Kamil Drakari Aug 5 '17 at 12:10 • Works offline and Dennis should be pulling. Good job, can't believe I didn't notice this! I always thought a truth machine had to print 1. – MD XF Aug 5 '17 at 17:06 • @MDXF It does print 1. The rules state that the input will either be a 1 or a 0 :P To make it print 1 always, just do :1/1%6 instead of %7 – TehPers Aug 7 '17 at 19:47 # 8th, 58 bytes Code : f getc '0 - dup 0 1 between if repeat dup . while then ; Explanation : f - Start of word definition getc - Get input from STDIN '0 - - Subtract 0's ASCII code to determine numeric input dup - Duplicate result to be used to run loop 0 1 between if - Check if input is either 0 or 1 repeat dup . while - Print either 0 once or 1 ad infinitum then ; - Exit word If input is not either 0 or 1, exit with no output. At the end of the program the stack is not empty. # 6502 machine code (C64), 17 bytes 20 FD AE 20 9E B7 8A 09 30 20 D2 FF C9 30 D0 F9 60 Online demo This is position independent code, you can enter it at any position in RAM and call it, so it doesn't need a load address. Assuming you put it at C000 (that's the case in the online demo), call it like sys49152,0 or sys49152,1 -- any other input is undefined. Explanation: 20 FD AE JSR$AEFD    ; consume comma
20 9E B7    JSR $B79E ; evaluate number, result in X 8A TXA ; transfer X to A 09 30 ORA #$30     ; convert to numeric character
20 D2 FF    JSR $FFD2 ; output character C9 30 CMP #$30     ; compare with '0' character
D0 F9       BNE *-5      ; not equal? Then jump back to output (-7)
60          RTS          ; return

# Excel VBA, 20 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and output 1, infinitely if [A1] else 0

While[A1]:?1:Wend:?0

# Whitespace, 40 bytes

Note that the only valid characters are space, tab, and linefeed, so they are represented here with S, T, and L, respectively. Comments are also given.

I used this interpreter to write and test this program (warning: crashes browser window upon input of 1).

SS L   # push 0
SLS    # duplicate
TTT    # retrieve
LSS L  #label "" (blank label name, why not?)
SLS    # duplicate
SLS    # duplicate
TLST   # printi
SS STL # push 1
TSST   # subtract
LTS L  # jz label "" (jump to blank label if input-1=0)

Three consecutive linefeeds (LLL) are usually required to end program execution at a point, but that interpreter doesn't seem to mind if you leave them out. If they have to be added in, the score would instead be 43 bytes.

• The interpreter defines the language, so the missing LLL should be completely fine. – Esolanging Fruit Sep 4 '17 at 5:32

# Pyth, 5 bytes

Like my Python answer, but in Pyth

WQ1)0

Explanation:

WQ1)      While Q, print 1. 1 = true, 0 = false; end While
0         Print 0

If input is 1, 0 is never reached, if input is 0, 1 is never reached.

Try it online!

# Implicit, 5 4 bytes

$(%) Try it online! Prints 00, which is equal to 0 Pretty simple:$(%)
$« integer input »; (.) « do..while top of stack true »; % « print top of stack »; « implicit integer output »; # ><>, 6 Bytes ::n?!; Input is assumed to be on the stack. It's duplicated twice, printed, and checked if it's non-zero. If it's non-zero, skip the end program command and loop around. Note that this does not print any spacing between the 1s. # Husk, 5 bytes ¶?∞;I Try it online! ### Explanation ? I -- if the input is truthy ∞ -- repeat it infinitly many times ; -- else create singleton list ¶ -- join by newlines Thanks @H.PWiz for golfing off 1 byte! • 5 bytes: ¶?∞;± or, if string input is valid: ?∞;i – H.PWiz Nov 21 '17 at 21:06 # GolfScript - 13 bytes ~{.}{.p}while Basically a while(arg){ print(arg) } print(arg) GolfScript doesn't have a real-time STDOUT, everything is printed from the stack to the console at the end of the execution, it has to be stopped manually. • – FedeWar Nov 21 '17 at 21:27 ## Evil, 74 bytes fjzaeeeaeeawbmxruuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuusbaeeeaeew A program that will request for a character of input. Every lowercase letter corresponds to a different instruction. Here's an analysis. f: goes Forward in the program and searches for the closest marking character, or m. This skips all of the code that will continuously output 1 to stdout. jzaeeeaeeawb: Continuously output 1 to stdout. The character b searches Backwards for the marking character. However, at this point the marking mode is set to 'alternate', so instead of searching for m, it's searching j, which is at the beggining. The random amount of es with a and z set the counter, or accumulator, to the ASCII representation of 1. w would do what you might think: Write the value of the accumulator to stdout. mxr: This is executed right after f. The marking character has now been found, and we continue with x, which switches the marking mode from 'standard' (m) to 'alternate' (j). Then, r Reads stdin for a character and sets the accumulator to the ASCII representation of the input, which would be either 48 for 0 or 49 for 1. uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuusb: Each u decrements the accumulator. The whole operation brings the accumulator down from 48 to 0 or 49 to 1. This is crucial for the following command; the letter s will Skip the next command only if the value of the accumulator is 0. That next command searches backwards for j, which goes all the way back to outputting 1 to stdout. Note that I could probably shorten the amount of bytes here by replacing some us with es, which weave the accumulator. aeeeaeew: Now, if the accumulator had hit 0, this snippet puts the accumulator back to 48, or 0, and w Writes the accumulator value to stdout. Original interpreter in Java: http://web.archive.org/web/20070906133127/http://www1.pacific.edu/~twrensch/evil/evil.java # SNOBOL4 (CSNOBOL4), 38 bytes N =INPUT L OUTPUT =N GT(N) :S(L) END Try it online! N =INPUT ;* read input as n L OUTPUT =N ;* print input GT(N) :S(L) ;* if n > 0, goto L END # Acc!!, 39 37 bytes N Count i while _%2-i%2+1 { Write _ } Try it online! This takes input through N, then prints the input _ until the equation _%2-i%2+1 is 0. This looks like: 48 48%2-0%2+1 => 1 48%2-1%2+1 => 0 48%2-2%2+1 => 1 48%2-3%2+1 => 0 49 49%2-0%2+1 => 2 49%2-1%2+1 => 1 49%2-2%2+1 => 2 49%2-3%2+1 => 1 This is shorter than the easy approach (39 bytes): N Write _ Count i while _%2 { Write _ } Try it online! # AWK, 20 bytes {do{print}while($0)}

This is the first thing I came up with. I tried to come up with something clever more clever but they were all longer.

Try it online!

# C (gcc) , 42 bytes

main(t){gets(&t);do puts(&t);while(t-48);}

Try it online

## Wumpus, 6 bytes

Iv=O=:

Try it online!

### Explanation

In Wumpus, the IP gets reflected off the program boundary (instead of wrapping around or terminating). Since there is no redirecting control flow in this program, the IP simply bounces back and forth, executing a loop with loop body

Iv=O=:=O=v

Let's go through this:

I   Read an integer N from STDIN. On subsequent iterations, this will push a zero.
v   Bitwise OR. On the first iteration this ORs the input with an implicit zero
which does nothing. On subsequent iterations, this gets rid of the zero that
was just pushed.
=   Duplicate the input.
O   Print it to STDOUT.
=   Duplicate it again.
:   Compute N/N. For input 0, this ends the program, due to the attempted division
by zero. For input 1, this just gives back 1.
=   Duplicate the input.
O   Print it to STDOUT.
=   Duplicate the input.
v   Bitwise OR. Just gets rid of one copy of the input.

# ShinyLisp, 22 bytes

+:Ge _&^:Pu~:I:P^~N:Qx

I figure now is as good a time as any to introduce my new golfing language. It's still largely a work in progress, but it's usable.

Ungolfed:

(= (gets))
(loop '% (puts) (cond (p %) () (quit)))

Explanation:

(= (gets))       -- Reads a line of user input and assigns it %
(loop '% ...)    -- Loop forever using % as the (constant) loop value
(puts)           -- Print the value of %
(cond (p %) ...) -- If % (treated as a number) is nonzero then...
()               -- Do nothing
(quit)           -- Else exit the program

# Linotte, 52 bytes

a:
e est un nombre
début
demande e
e!
tant que e,e!

Linotte is a french programming language aimed at beginners. Translated into English:

a:
e is a number
start
e!
while e, e!

e! is shorthand for affiche e, which means "display e".

DO
PRINT*,I
IF(I==0)EXIT
ENDDO
END

Try it online!

# brainfuck, 25 bytes

Note: This is a different "language" than this answer, because it requires a brainfuck variant that exits when the memory pointer is moved left of the initial position, whereas this needs a brainfuck variant that can read and write left of the initial position.

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

Try it Online!

## Explanation

,.             Read and print a character.
[[<+>->+<]>-]  Write the range from the code point of the character down to one.
<+[<<]>        Go to the first element in the sequence if the length is odd, otherwise
go to the cell before.
[.]            Print the value at the pointer forever if the input is odd, determined by
if the pointer is on or outside the sequence of numbers in memory.

Here are two other interesting solutions i found, which may be golfable (29 bytes each):

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

## Lua, 41 bytes

a=io.read()while q~="0"do print(a)q=a end

Explanation:

a=io.read(): read input from user and store in variable a

while q~="0"do: compares q to the string "0", q starts as nil, which isn't "0" so the loop runs at least once. Because the input is a string we have to compare with the string "0", not the number 0

print(a)q=a: prints a (1 or 0) and sets q to a, so if a = "1" the loop continues, if a = "0" the loop stops

end: end of loop, like } in other languages

Whitespace is not needed after parenthesis/quotation marks, for example print(a)q=a is equivalent to print(a) q=a

• Hi and welcome to PPCG! – Herman L May 26 '18 at 10:48

# Rust, 90 bytes

use std::io::*;fn main(){let

Try it online!

# FerNANDo, 37 bytes

_ _ _ 1 _ _ _ _ C
C
0 0 1 1 0 0 0 C
C

Try it online!

# Z80Golf, 9 bytes

00000000: cd03 80ff fe30 20fb 76                   .....0 .v

Try it online!

### Disassembly

start:
call $8003 loop: rst$38
cp $30 jr nz, loop halt The Z80Golf machine initializes whole memory and all registers to zero before loading the program. call$8003 calls getchar, which takes a byte from stdin to register a. On EOF, the register a does not change and the carry flag is set.

rst $38 simulates a call to putchar which prints the register a. The function is actually at$8000, so PC slides through $00 bytes (NOPs) in the memory until it hits the address$8000.

The rest is just a straightforward do-while loop in assembly, no tricks involved.

# Z80Golf, Byte IO, 8 bytes

00000000: cd03 80ff b820 fc76                      ..... .v

Try it online!

### Disassembly

start:
call $8003 loop: rst$38
cp b
jr nz, loop
halt

The only difference is the use of cp b, where b is used in place of constant zero.

# Z80Golf, Byte IO, Tricky version, 8 bytes

00000000: cd03 80b8 2002 ff76                      .... ..v

Try it online!

### Disassembly

start:
call $8003 cp b jr nz, infinity rst$38
halt
infinity:

If the input is zero, rst $38 and then halt is executed, exiting the program normally. Otherwise, something weird happens: • PC goes to infinity:, slides through NOPs, and then putchar is executed. • The putchar has a ret instruction, so sp becomes 2 and execution is returned to the address$03cd.
• Then putchar is executed again. sp becomes 4, pc is $b880. • Now pc wraps around and comes to$0000, the start of the program.
• call $8003 is run, which overwrites the program so$80b8 becomes $0300. • getchar sets the carry flag, but we don't care anyway. EOF is hit so a is untouched. • Now cp b became nop, but jr nz, infinity is intact. Again putchar is run, sp becomes 6, pc is$0220. putchar again, sp = 8, pc is $76ff, putchar again, sp = 10 =$000a, pc = $0000. • The call$8003 became call $0303, which now effectively calls putchar instead. No problem, now one loop just prints a twice. Note that a call leaves$0300 to the memory, but fortunately $00 is NOP and$03 is inc bc, which does not affect the program's logic. (Single-byte inc does affect the flags, but double-byte ones don't, so jr nz isn't affected either.)
• The call is now a heat wave filling the memory with $0300. Eventually, sp wraps around to$0002 again, and finally overwrites $cd03 into$0300, deleting the call .

The heat wave is finally over, and the only thing left is:

jr nz, infinity
rst $38 halt infinity: The conclusion is that we have an infinite loop printing 1 as a byte. Note that putchar is NOT an actual piece of code in memory. It is "simulated" when the PC hits$8000, along the ret instruction.

# Pascal (FPC), 54 bytes

var a:word;begin read(a);repeat write(a)until a<1 end.

Try it online!