I overloaded some C# operators to get a pseudo version of the Brainfuck symbols in the effort of understanding the flow of this language.
I got this version:
void Main()
{
/*
* Write `Hello World!`
* using operators overloading for brainfuck symbols
*/
var _ = new brainfuck();
_ = + + + + + + + + + + _ ; // set cell #0 to 10
while (_)
{
_ = + + + + + + + (_ > 1) ; // add 7 to #1
_ = + + + + + + + + + + (_ > 1) ; // add 10 to #2
_ = + + + (_ > 1) ; // add 3 to #3
_ = + (_ > 1) ; // add 1 to #4
_ = - (_ < 1 < 1 < 1 < 1) ; // decrement 0
}
_ = ~ + + (_ > 1) ; // write 'H'
_ = ~ + (_ > 1) ; // write 'e'
_ = ~ + + + + + + + _ ; //write 'l'
_ = ~ _ ; //write 'l'
_ = ~ + + + _ ; // write 'o'
_ = ~ + + (_ > 1) ; // write ' '
_ = ~ + + + + + + + + + + + + + + + (_ < 1 < 1) ; // write 'W'
_ = ~ (_ > 1) ; // write 'o'
_ = ~ + + + _ ; // write 'r'
_ = ~ - - - - - - _ ; // write 'l'
_ = ~ - - - - - - - - _ ; // write 'd'
_ = ~ + (_ > 1) ; // write '!'
_ = ~ (_ > 1) ; // write '\n'
}
public class brainfuck
{
private List<int> cells;
private int currentCell;
public brainfuck()
{
cells = new List<int>{0};
}
public static brainfuck operator + (brainfuck bf)
{
bf.plus();
return bf;
}
public static brainfuck operator - (brainfuck bf)
{
bf.minus();
return bf;
}
public static brainfuck operator > (brainfuck bf, int pos = 1)
{
bf.right();
return bf;
}
public static brainfuck operator < (brainfuck bf, int pos = 1)
{
bf.left();
return bf;
}
public static brainfuck operator ~ (brainfuck bf)
{
bf.write();
return bf;
}
public static brainfuck operator ! (brainfuck bf)
{
bf.read();
return bf;
}
public static implicit operator bool (brainfuck bf)
{
return bf.has_data();
}
private int plus()
{
return ++cells[currentCell];
}
private int minus()
{
return --cells[currentCell];
}
private void right()
{
if (currentCell + 1 == cells.Count)
cells.Add(0);
currentCell++;
}
private void left()
{
if (currentCell > 0)
currentCell--;
}
private int current()
{
return cells[currentCell];
}
private void write()
{
Console.Write((char)current());
}
private void read()
{
var input = Console.ReadLine();
int value = Int32.TryParse(input, out value) ? value : 0;
current(value);
}
private bool has_data()
{
return current() > 0;
}
private void current(int value)
{
cells[currentCell] = value;
}
public override string ToString()
{
return String.Join(",",cells);
}
}
I had to cheat with the []
command pair using the while
statement and the flow is very odd from the point of Brainfuck reader, since the <,>
commands are before the +,-
in the original Hello World! example, and with C# program are in the opposite way.
Do you think I can get a closer version to Brainfuck than the current one?