Implementing Control Structures at Brainfuck

For the uninitiated, Brainfuck is a Turing-complete language with a total of 8 commands, all of which have literal equivalents in C:

bf c ---------------------- > ++ptr; < --ptr; + ++*ptr; - --*ptr; . putchar(*ptr); , *ptr=getchar(); [ while (*ptr) { ] } 

On any Linux distribution that has a package manager, you must find and install the beef package, the Brainfuck interpreter, so you can play at home.

As you can see above, Brainfuck has a one , […] management structure that translates to C as:

 while (*ptr) { … } 

Which gives you control over IF VAR = 0 THEN GOTO 10 from BASIC. The following will call getchar() until it returns 0 :

 , # *ptr = getchar(); [ # while (*ptr) { >, # *(++ptr) = getchar(); ] # } 

But what if I only want to read the new line char \n ? After some difficulty wrapping my brain around how it can be adapted to work as a simple if , I came up with the following:

 , # *ptr = getchar(); /* store input */ ---------- # *ptr -= 10; /* test for \n by subtracting 10 before loop */ [ # while (*ptr) { /* if *ptr == 0, last char read was \n */ ++++++++++ # *ptr += 10; /* wasn't \n, add 10 back to val under ptr */ >, # *(++ptr) = getchar(); ---------- # *ptr -= 10; ] # } 

(If anyone has a better way to do this, please let me know)

Now let's say that I want to test the output of this loop on \r in addition to \n . How can I test this, given that I have only one opportunity to exit the loop? My goal is to be able to emulate switch nested if or if/else if s.

+7
computer-science turing-machines brainfuck
source share
3 answers

I have not looked at the link yet, but I believe that the Ashwa answer is probably more universally useful ... however, did not dare to let my fingers give out some kind of Brainfuck, I decided that now it was as good as everything and I was able to get the following, which I think works.

The second half is only for listing what was captured in the first part. Besides, I won’t lie, my brain really feels completely β€œfucked” after trying to work it out ... A very aptly named language, hehe.

 + [ >, ---------- [ --- [ +++++++++++++ >> ] ] < [ >> ] < ] ++++++++++++ [ < ] > [ .> ] 
+3
source share

Here are the algorithms for doing the basic logical, but complex work for Brain F * ck :)

+4
source share

See this page for a description of how to start with a single BF control structure and define a series of increasingly complex sequences representing more complex operations.

+3
source share

All Articles