Monday, August 1, 2011

Playing GOLF, hole 1

A while back I started with the idea of writing the Game Of Life test first using F#. I already blogged some about this, but this week I finally found the time to actually implement all this from start to finish. I did start all over again though, since my last post didn't really contain a functional starting point. And I did give it some tries to get the code right and I also took a peek at the Scheme implementation that can be found at this link (hey, it's been five years since I've done functional programming, I am allowed to make mistakes and to see what others have done). So it is quite possible that there are similarities between my implementation and the Scheme version. There is also an F# version that can be found at that site, but it's implementation uses a bit too many nested for loops for my liking.

First of all, I rewrote my first test. The idea of having cells that know how many living neighbours they have, was nice at first, but with this implementation I wanted to start of with a gameboard of all dead cells. For my first most simple test, I started of with: If I have all dead cells, than after zero generations all cells should still be dead.

 namespace GolF.Tests
 
 open NUnit.Framework 
 open FsUnit 
 open GOL 
 [<TestFixture>] 
 type ``Given a dead gameboard`` ()= 
   let gameboard =  
     [[0; 0; 0]; 
     [0; 0; 0]; 
     [0; 0; 0]] 
   [<Test>] member test. 
    ``When I ask for generation 0, should not change gameboard`` ()=  
     conway gameboard 0 |> should equal gameboard  

To make the test compile I added the conway function, which just returned a string (I didn't want to make the test green, yet).

 module GOL 
 let conway gameboard n = 
   "test"  

This made the test compile, but off course it was still red.


To make the test pass, I altered the conway function a bit.

 let conway gameboard n = 
   gameboard  

Plain and simple. Implement the most simple thing to make the test turn green.

So, time to add a second test: If I ask for generation 1 of a dead gameboard, the gameboard should still be dead.

   [<Test>] member test. 
    ``When I ask for generation 1, gameboard should still be dead`` ()= 
     conway gameboard 1 |> should equal gameboard  

This test actually immediately passes with the current implementation, but it is a good test to have around once we start adding the actual code of calculating generations.

That's all for the first hole of playing GolF, on to the second one.

No comments:

Post a Comment