Brainfuck Interpreter in two tweets.
Previous article Code Golf: Game of Life raised some interest, and I decided to proceed. Today’s problem is a Brainfuck Interpreter.
Brainfuck is an esoteric programming language, famous because of its small command set. It is based on array of cells (Turing Tape) and pointer to this array. There are only 8 commands:
>move to the next cell
<move to the previous cell
+increment value in the current cell
-decrement value in the current cell
.print char with ascii value of current cell
,read ascii value for input char to the current cell
[start loop until value of pointer is not zero
That’s all. Brainfuck is Turing Complete language, that means it capable to implement any program. If you crazy, of course.
Final version took
280 characters in Clojure:
1 2 3 4 5
Exactly 2 tweets.
Translating to more readable code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
So, what’s happening there?
Function arguments are parameters of our tape and brainfuck program.
ais an array represents finite tape
e.g (int-array 100)
ptis an atom - pointer to the tape
pcis an atom - pointer to the command list
act decides which action to perform depending on current command,
loop allows us to move command pointer inside a loop,
while-do loop executes commands until they exhausted. Simple enough.
To make our interpreter more friendly we create function
parse that accepts
string - program, written in brainfuck.
1 2 3 4 5 6
Print “Hello, world”
1 2 3 4
Input 5 characters and reverse print them
More complex program need nested loops, which is not supported by this version (for the sake of small size!)
History of implementation, nested loops and more available here
P.S. This version is not “fully-featured” brainfuck interpreter.
- It does not work for inifinite tape
- Cell datatype is fixed and not assumed to be cyclic. For example, if cell type is unsigned byte
255 + 1 != 0and break interpreter
- Only unsigned types supported
- Nested loops are not allowed
- No error handling
But, you are welcome to improve it!