esolang
Learn · Ideas0 languages show it

Reading until the end of input

A loop that reads and prints until there is nothing left. Every language needs a way to notice the end, and they disagree on what it is.

●○○ easy

The idea

A program that copies its input to its output is called cat. It reads a byte, prints it, and repeats. The hard part is the end, where the program must notice there is no more input.

Read the story

Each language has a signal for the end. In this implementation of brainfuck, , stores 0. In the kernel, READ gives −1, and LEFT says how many bytes are still unread.

Step by step in brainfuck

Another brainfuck stores −1 (255) at the end.

cat, when the end reads as 0

Expected output

hello

Output


  • , reads the first byte. [ enters the loop if it is not 0.
  • ., prints it and reads the next. ] loops while that byte is not 0.
  • At the end , stores 0, so the loop stops. A real 0 byte in the input would stop it too.

cat, when the end reads as −1

Another brainfuck stores −1 (255) at the end. + turns 255 into 0, so the loop can test it; - undoes the + before printing.

Expected output

hello

Output


Side by side

LEFT pushes how many bytes are unread, and TIMES … END repeats that many times.

The kernel counts what is left

LEFT pushes how many bytes are unread, and TIMES … END repeats that many times. No test for the end is needed.

Expected output

hello

Output


Befunge tests for −1

~ reads a character (−1 at the end). :1+! is 1 only at the end. # jumps over @, and _ turns left onto @ at the end, or goes right to , to print.

Expected output

hello

Output


Why the kernel has LEFT

Without LEFT, "read until the input ends" needs an IF … ELSE inside a loop, and program search could not…

Without LEFT, "read until the input ends" needs an IF … ELSE inside a loop, and program search could not reach that. LEFT was added to the kernel as a deliberate hint to the search.