pseudo brainfuck with the help of C# operator overloading




void Main()
{
/*
* Write `Hello World!`
* using operators overloading for brainfuck symbols
*/
var _ = new Brainfuck();
_ = + + + + + + + + + + _ ; // set cell #0 to 10
_ = _[() => {
_ = + + + + + + + (_ > 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)
{
bf.Right();
return bf;
}
public static Brainfuck operator < (Brainfuck bf, int pos)
{
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 Brainfuck this[Action action]
{
get
{
while (this)
{
action.Invoke();
}
return this;
}
}
public static implicit operator bool (Brainfuck bf)
{
return bf.HasData();
}
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 = int.TryParse(input, out value) ? value : 0;
Current(value);
}
private bool HasData()
{
return Current() > 0;
}
private void Current(int value)
{
cells[currentCell] = value;
}
public override string ToString()
{
return String.Join(",",cells);
}
}
view raw brainfuck.cs hosted with ❤ by GitHub

Comments

Popular posts from this blog

IIS 7.5, HTTPS Bindings and ERR_CONNECTION_RESET

Verify ILogger calls with Moq.ILogger

Table Per Hierarchy Inheritance with Column Discriminator and Associations used in Derived Entity Types