Simple Cell Automata in Haskell


To further help me improve my Haskell skills I’ve started writing an implementation of Conways Game of Live. The rules here are simple;

  • The cells are laid out in a grid – my implementation assumes a square
  • If any cell is “alive” and it has more than three neighbours, then the cell dies
  • If any cell is “alive” and it has fewer than two neighbours, then the cell dies
  • If any cell is not alive and it has between two and three neighbours, then it comes to life

I also wanted my cell automata to be nicely visible so I decided to use Glade and Gtk2Hs to make a nice GUI for it.

Getting Everything Installed

I already had GHC installed, so all I need to install was everything else. Firstly, use the package manager to install Glade. This was easy, the rest is easy to but involves using cabal.

cabal install alex
cabal install gtk2hs-buildtools
cabal install gtk
cabal install glade

To use your Glade/GTK stuff with GHC you need to use this incantation;

ghc -package gtk --make MyProgram

Also, when using Glade the project file format needs to be changed from “GtkBuilder” to “Libglade”.

The Code

My code can be found in BitBucket here; Cell Automata

The cell automata algorithm works okay see the “evolve” method. I’m currently stalled on trying to make it work nicely in the GUI.

I got stuck when trying to calculate the square root of an integer (and receive a rounded/truncated integer as the result). I couldn’t make that work so I borrowed/stole some code from to work that bit out for me. I couldn’t make the Haskell sqrt work properly.

Edit: I got this fixed. To get an integer square root of an integer, the following incantation is used

floor (sqrt (fromIntegral (length xs)))

In the above, xs is the list containing my cells world. This is safe to do because in my implementation the size of the world is always a square number. I’ve yet to run hlint over my code to check that it is sensible. Edit ends.

If anyone can offer any insights into how to create a kind of animation thread (for want of a better phrase) to handle the rendering the evolution of the world I’d be very grateful!

Comments always welcome.

Edit: I finally got it all working, including a UI in HOpenGL. The biggest problem I’m facing now is that there GOL algorithm is very ineffecient for large world sizes, I’m guessing this is because it does a lot of list traversals per cell.

I should also mention the following three sites which proved to be invaluable.

  1. Michi’s blog which I “borrowed” the majority of the OpenGL code and module layout from
  2. Andre W B Furtado tutorial for the IORef help
  3. My Awesome Blag – which appears to be the only place on the Internet which shows how to use the timer callback

Comments are closed.


Get every new post delivered to your Inbox.

%d bloggers like this: