It has been bugging me for a while that while I understand how the basics of Brainfuck works, I can't get a firm grasp on the advanced features of the language. So I started to re-evaluate what I know about the language from the ground up.
Brainfuck's memory consists of a tape of cells. Every cell can be modified by pointing the pointer at it and incrementing or decrementing it's value.
The most basic operators are +
, -
and .
. These operators will respectively increment, decrement and print the data at the current cell. The print operator will take the current value and put the corresponding ASCII character on screen.
To print a basic sentence:
Hello, World!
I've written the following:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. Increment to 'H' and print
+++++++++++++++++++++++++++++. Increment to 'e' and print
+++++++. Increment to 'l' and print
. Value is already at 'l' so just print
+++. Increment to 'o' and print
-------------------------------------------------------------------. Decrement to comma and print
------------. Decrement to ' ' and print
+++++++++++++++++++++++++++++++++++++++++++++++++++++++. Increment to 'W' and print
++++++++++++++++++++++++. Increment to 'o' and print
+++. Increment to 'r' and print
------. Decrement to 'l' and print
--------. Decrement to 'd' and print
-------------------------------------------------------------------. Decrement to '!' and print
Writing Brainfuck in this style to print a sentence is pretty straightforward. Iterate over the sentence and do the following per character:
- Calculate the difference between the current character and the previous
- Write either as many
+
or-
as the difference between characters.+
if current character is higher than previous character,-
if lower than previous character - Write
.
to print current character
The result as seen above isn't as bad as it looks. It's very memory efficient since all operations are made on the same cell. But speed is also important. Unfortunately I do not know how to properly time Brainfuck executions (yet).
I'm fairly sure this is not the 'best'/'idiomatic' way of writing this. I know Brainfuck supports a while
construction which seems like a good idea here, but I haven't found the most obvious implementation yet. I've seen Simon's method, but I'm not at that level yet.
As usual I don't care about the length of the code (Brainfuck isn't JavaScript after all), but I'm definitely repeating myself an awful lot.
How bad is my current implementation? Pointers as to how to gradually improve this to the more standard style of Brainfuck (using loops instead of repetition) are welcome.