Saturday, November 10, 2007

brainfuck

Have you ever needed a programming language that's incredibly difficult to understand, has an extremely small compiler, and is still Turing complete? That's brainfuck.

Brainfuck has only 8 commands.
<> Move pointer right
+ Increment the number the pointer points to
- Decrement the number the point points to
, Store input in where the pointer points
. Print the ASCII representation of the number the pointer points to
[ ] Repeat the commands in the loop while the number the pointer points to is not zero
Any other character is considered a comment.

For the non-programmers, here's an analogy. Imagine, you have a very, very long line of boxes, arranged left to right. Each box holds a number, and you can only look at one box at a time. When you begin, all boxes hold zero.
<> Means you look in the box to the immediate right of the box you're at now.
+ Means you add one to the number in the box you're at.
- Means you subtract one from the number in the box you're at now.
, Means someone else tells you what number to put in the box you're at.
. Means you tell that other person what number is in the box you're at.
(Note that input and output use ASCII, so if the input is A, the number stored is 65, and if the number stored is 49, the character output is 1.)
[ ] Do everything within these until the box you're at is zero.

Here's an example of the "Hello, world!" program in brainfuck:
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

Here's a program that takes two numbers from the user, adds them and gives the answer.
,>,[-<+>]<.
Here's what happens:
, Stores user input in the first box
> Moves to the second box
, Stores user input in the second box
[-<+>] while the second box is not zero, subtract one from the second box, move to the first box, add one to the first box, move back to the second box.
< Move to the first box
. Output result.

Obviously, complicated programs quickly become extremely difficult to understand. Brainfuck really doesn't have any point, except for its very small compiler. But it's fun anyway.

2 comments:

Anonymous said...

Is there a reason they call it Brainfuck?

And not to sound stupid, but maybe you could show what how those two examples you showed work. I have done a little futzing with programming, but I'm a bit confused as to what it's doing.

I like the analogy tho, i found it pretty clever.

Alex Strinka said...

It's called brainfuck (with a lowercase b) because it, well... fucks with your brain.

I showed how the second program worked command by command. For the first one, it just stores the various values of the characters into the boxes, and then outputs them.