It’s been a long time since I posted! I have now started back at university, moved in to a new flat and also moved this blog to the UK version of The Rackspace Cloud. The latency is much lower to the server now and there is far less lag in SSH and other services. Anyway, on with the randomness…
A good friend of mine, Ste, recently reintroduced me to Brainfuck. For the uneducated (and right now, probably offended), Brainfuck is an extremely lightweight and minimalistic programming language. It’s really designed to be a muse for programmers that are bored as far as I can tell.
In any case, after playing around with it for a while, I thought I’d have a go at writing a PHP implementation of the interpreter. In fact I wrote two implementations, a lovely OOP-style one, and also a really short minified one to see just how small I can make the interpreter.
The first implementation I wrote is the OOP version. It’s a bit over-complicated and full of itself but hey – isn’t all decent programming that way. You can check out the source in my work repo - http://work.damow.net/work/
The more concise version of my interpreter (also downloadable from the work repo link above) is not exactly written with human readability in mind. It still works fine however. Essentially it is a function that takes a string of Brainfuck program characters and optionally an array of input byte values (read by the , character in Brainfuck). All in 441 bytes of PHP. I know I know, I’m just cruising for some pro to come and blast me out of the water with a 50-byte beast, but it’s the trying that counts!
<?php function p($p,$i){$p=str_split($p);$d=array();$o='';$c=$p[0];
while($c){if($c=='+')$d[key($d)]++;if($c=='-')$d[key($d)]--;if($c==
'.')$o.=chr(pos($d));if($c==','){$d[key($d)]=pos($i);next($i);}if($
c=='>')if(!next($d))$d[]=0;if($c=='<')prev($d);if($c=='['&&pos($d)=
=0){$l=1;while($l){$n=next($p);if($n=='[')$l++;if($n==']')$l--;}}if
($c==']'&&pos($d)){$l=1;while($l){$n=prev($p);if($n==']')$l++;if($n
=='[')$l--;}}$c=next($p);}return $o;}?>
In terms of future developments, I was thinking during my chat with Ste about Brainfuck that rather than try to expand the language by adding more characters to the command set (which I think would take away a bit of the charm from the language), one could add more functionality by mapping high-range pointers to other outputs, for example pixels on the screen to provide graphical output. It would be really nice to write a Brainfuck workshop suite to provide functionality like that, but I don’t like to linger on one project unnecessarily for too long.
I’ll try to post more regularly, and make my posts include less of the “f” word in future, I promise.
Laters