Brainfuck

October 4, 2011

In 1993, Urban Müller invented the brainfuck programming language, which is a simple-minded programming language, similar to a Turing machine, with a very terse syntax. The data store consists of 30000 cells, each a single byte initialized to 0; a data pointer points to one of the cells. Programs consist of the eight characters +-.,[] with the following meanings:

< move the data pointer one cell left> move the data pointer one cell right+ increment the cell at the current data pointer- decrement the cell at the current data pointer. output the cell at the current data pointer as a character, input the next character to the cell at the current data pointer[ if the cell at the current data pointer is zero, move the instruction pointer to the matching ]] move the instruction pointer to the matching [

The brainfuck interpreter runs through a program performing each instruction as it appears, ignoring all characters other then +-.,[], advancing the instruction pointer after each instruction (including after [ and ]); a program halts by running off its end. Here’s a sample brainfuck program, which prints “Hello World!” when it is run; additional sample programs appear on the next page:

Like this:

Related

14 Responses to “Brainfuck”

It looks like that the above brainfuck code is slightly wrong. It should be:
++++++++++[>+++++++>++++++++++>+++>+<<<++.>+.+++++++..+++.>++.<.+++.——.——–.>+.>.
You replaced <<<< by >>. The correct code is on page 2.

Here’s my python 3 version. It is essentially the same as other’s above.

A minor optimization is to implement looping using a loop stack. When ‘[‘ is encountered, ip (the instruction pointer)
is pushed on the loop stack (ls)(at this point ip points to the instruction after the ‘[‘). When a ‘]’ is encounterd,
d[dp] is tested. If d[dp] is non-zero a jump to the top of the loop is done by loading ip from the top of the loop stack.
If d[dp] is zero, the loop stack is popped and execution continues after the ‘]’.

Well, a loop is just a subroutine, so getting in/out of it should be handled by the evaluator.
Parse the string into a tree, then eval the tree. Loops are then just subtrees that need to be evaluated before we can continue.