Just for fun brainfuck'a'like textprocessor

janderson askme at me.com
Tue May 22 22:52:53 PDT 2007


Gregor Kopp wrote:
> Hi, I've just written this small peace of thing.
> Have fun with it.
> 
> I think everyone should read code from others, so I for myself want to 
> provide you my code. If you have improvements: post it ;)
> 
> 

Nice work!

BTW: did you see Gregor Richards compile time version?

Gregor Richards
------------------------------------------------------------
ctbf.d:
------------------------------------------------------------
module ctbf;

import std.cstream;
import std.stdio;

static char[] ctbf(char[] bf)
{
     char[] code = `
     byte[] mem;
     uint memptr = 0;
     mem.length = 1;
     void expand() {
         if (mem.length <= memptr) {
             mem.length = memptr + 1;
         }
     }
     `;

     foreach (c; bf) {
         switch (c) {
             case '>':
                 code ~= "memptr++; expand();\n";
                 break;

             case '<':
                 code ~= "memptr--;\n";
                 break;

             case '+':
                 code ~= "mem[memptr]++;\n";
                 break;

             case '-':
                 code ~= "mem[memptr]--;\n";
                 break;

             case '[':
                 code ~= "while (mem[memptr]) {\n";
                 break;

             case ']':
                 code ~= "}\n";
                 break;

             case '.':
                 code ~= "dout.write(cast(char) mem[memptr]);\n";
                 break;

             case ',':
                 code ~= "din.read(mem[memptr]);\n";
                 break;

             default:
         }
     }

     return code;
}

int main()
{
     mixin(ctbf(import("helloworld.bf")));
     return 0;
}


More information about the Digitalmars-d-learn mailing list