31 Mar 2008, 11:25 p.m.

PHPTuring

A few years ago, as an exercise in Test-Driven Development, I wrote a Turing machine simulator in PHP and imaginatively named it PHPTuring.

I had completely forgotten about it until today, when I dug it out for another look. Truth be told, I still haven't seen a Turing machine done any better in PHP, and apart from a few syntactical niceties (removing closing PHP tags as per the Zend way, neatening up the PHPDoc blocks) I'm actually pretty comfortable with the code.

Using it is a breeze. It reads pipe-separated tapes and newline plus pipe-separated instruction sets like so:


<?php

$prog = '0|1|1|R|0\n0||1|R|1\n1|1|1|R|1\n1|||L|2\n2|1|||stop';
$tape = '1|1|1|1|1|1||1|1|1|1|1|1|1|1';

$machine  = new Machine();
$compiler = new SimpleCompiler();
$parser   = new SimpleTapeParser();
$debugger = new SimpleDebugger();

$debugger->watch($machine);

header('Content-type: text/plain');
$machine->run($compiler->compile($prog),
              $parser->parse($tape));

It should work with other formats, so long as someone writes parsers for them. Similarly, the debugger is just an Observer that dumps the state and tape to the screen at each step, but it could easily do something more subtle some day.

The code ships with full tests, and is available for download on PHPTuring's Sourceforge download page.

So why am I banging on about it here? I don't know. Maybe just because I like it, because it was the first afternoon's coding that really got me test-infected, and because I'd be interested in any feedback.

Posted by Simon in PHP, Testing and Programming